相关疑难解决方法(0)

我可以在C++中从另一个构造函数(构造函数链接)调用构造函数吗?

作为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'关键字,但都失败了.

c++ constructor

879
推荐指数
10
解决办法
44万
查看次数

如何避免初始化程序列表中的代码重复

我的课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)

问题:是否有任何方法可以使代码更紧凑,减少“复制粘贴”?

c++ constructor

2
推荐指数
1
解决办法
54
查看次数

标签 统计

c++ ×2

constructor ×2