作为C#开发人员,我习惯于运行构造函数:
class Test {
public Test() {
DoSomething();
}
public Test(int count) : this() {
DoSomethingWithCount(count);
}
public Test(int count, string name) : this(count) {
DoSomethingWithName(name);
}
}
Run Code Online (Sandbox Code Playgroud)
有没有办法在C++中执行此操作?
我尝试调用类名并使用'this'关键字,但都失败了.
我的课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;
};
Run Code Online (Sandbox Code Playgroud)
除了基类的使用外,构造函数代码相同:
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")
{}
Run Code Online (Sandbox Code Playgroud)
问题:是否有任何方法可以使代码更紧凑,减少“复制粘贴”?