gpt4 book ai didi

c++ - 如何避免初始化列表中的代码重复

转载 作者:太空狗 更新时间:2023-10-29 23:48:41 26 4
gpt4 key购买 nike

我有 D 类继承自 B:

struct D: public B {
D(int b1, int p);
D(int b1, int b2, int p);
int p1;
float p2;
double p3;
std::string p4;
};

除了基类初始化外,构造函数代码是相同的:

 D::D(int b1, int p): B(b1)
, p1(p)
, p2(SomeFunc())
, p3(SomeOtherFunc() - 42)
, p4("abc")
{}

D::D(int b1, int b2, int p): B(b1, b2)
, p1(p)
, p2(SomeFunc())
, p3(SomeOtherFunc() - 42)
, p4("abc")
{}

问题:有没有办法让代码更紧凑,减少“复制粘贴”?

最佳答案

使用委托(delegate)构造函数。

// Assuming default value of b2 is 0.
D::D(int b1, int p): D(b1, 0, p) {}

D::D(int b1, int b2, int p): B(b1, b2)
, p1(p)
, p2(SomeFunc())
, p3(SomeOtherFunc() - 42)
, p4("abc")
{}

参见 http://www.stroustrup.com/C++11FAQ.html#delegating-ctor有关委派构造函数的更多信息。

关于c++ - 如何避免初始化列表中的代码重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55169685/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com