C++调用含多默认参数的构造函数,如何跳过不确定位置的参数?
解决构造函数默认参数过多的实用方案
针对你遇到的构造函数默认参数太多、修改末尾参数必须传递所有前置默认值的问题,这里提供几个可行的C++编程技巧:
1. 使用参数结构体+指定初始化(C++20及以上)
定义一个包含所有可选参数的结构体,给每个成员设置默认值,再重构构造函数以接受该结构体作为可选参数。调用时只需指定需要修改的参数,其余沿用默认值即可。
// 定义参数结构体,包含所有可选参数并设置默认值 struct OLEDstreamConfig { void (*fAlarm)() = NULL; int buffsz = 21*5; const uint8_t* font = u8g2_font_6x10_mr; int minx = 0; int miny = 11; int maxx = 120; int maxy = 60; int stepx = 6; int stepy = 11; }; // 重构构造函数 OLEDstream::OLEDstream(uint8_t num, const uint8_t* pins, const OLEDstreamConfig& config = {}); // 调用示例:仅修改stepy参数 OLEDstream oled(1, my_pins, {.stepy = 15});
2. 采用Builder设计模式
创建一个Builder类,通过链式调用设置需要修改的参数,最后生成目标对象。这种方式兼容所有C++版本,且代码可读性极强。
class OLEDstreamBuilder { public: // 初始化必填参数 OLEDstreamBuilder(uint8_t num, const uint8_t* pins) : num_(num), pins_(pins) {} // 链式设置各个可选参数 OLEDstreamBuilder& setAlarm(void (*f)()) { fAlarm_ = f; return *this; } OLEDstreamBuilder& setStepY(int stepy) { stepy_ = stepy; return *this; } // 其他参数的set方法依此类推... // 生成OLEDstream对象 OLEDstream build() { return OLEDstream(num_, pins_, fAlarm_, buffsz_, font_, minx_, miny_, maxx_, maxy_, stepx_, stepy_); } private: // 成员变量对应原构造函数参数,初始化默认值 uint8_t num_; const uint8_t* pins_; void (*fAlarm_)() = NULL; int buffsz_ = 21*5; const uint8_t* font_ = u8g2_font_6x10_mr; int minx_ = 0; int miny_ = 11; int maxx_ = 120; int maxy_ = 60; int stepx_ = 6; int stepy_ = 11; }; // 调用示例:仅设置stepy OLEDstream oled = OLEDstreamBuilder(1, my_pins) .setStepY(15) .build();
3. 重载常用场景的构造函数
不用覆盖所有参数组合,只针对实际会用到的场景重载构造函数。比如专门添加一个构造函数,接受必填参数和你需要修改的stepy,内部调用原构造函数并传入其他默认参数。
// 新增重载构造函数 OLEDstream::OLEDstream(uint8_t num, const uint8_t* pins, int stepy) : OLEDstream(num, pins, NULL, 21*5, u8g2_font_6x10_mr, 0, 11, 120, 60, 6, stepy) {} // 调用示例:直接传递stepy OLEDstream oled(1, my_pins, 15);
内容的提问来源于stack exchange,提问作者illustager
相关产品推荐
相关产品推荐

