#include <iostream>
#include <string>
// 定义颜色和线条宽度结构体
struct DrawOptions {
std::string color = "black";
int lineWidth = 1;
};
// 绘制圆形的函数
void drawShape(int centerX, int centerY, int radius, const DrawOptions& options = DrawOptions()) {
std::cout << "绘制圆形,圆心坐标: (" << centerX << ", " << centerY << "), 半径: " << radius
<< ", 颜色: " << options.color << ", 线条宽度: " << options.lineWidth << std::endl;
}
// 绘制矩形的函数
void drawShape(int topLeftX, int topLeftY, int width, int height, const DrawOptions& options = DrawOptions()) {
std::cout << "绘制矩形,左上角坐标: (" << topLeftX << ", " << topLeftY << "), 宽度: " << width
<< ", 高度: " << height << ", 颜色: " << options.color << ", 线条宽度: " << options.lineWidth << std::endl;
}
代码结构优化说明
- 参数封装:将颜色和线条宽度等可选参数封装到
DrawOptions
结构体中,这样在函数重载时,可选参数的传递更加清晰,也便于将来扩展更多的绘图选项。
- 默认参数:在函数声明中为
DrawOptions
设置默认值,使得调用者在不需要指定可选参数时,使用默认的绘图属性,简化了函数调用。
- 独立函数职责:每个重载的
drawShape
函数专注于绘制一种特定的图形,使得代码逻辑清晰,易于理解和维护。如果需要增加新的图形类型,只需要添加新的drawShape
函数重载即可,符合开闭原则,提高了代码的扩展性。