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

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

作为C#我习惯于运行构造函数:

class Test {
    public Test() {
        DoSomething();
    }

    public Test(int count) : this() {
        DoSomethingWithCount(count);
    }

    public Test(int count, string name) : this(count) {
        DoSomethingWithName(name);
    }}

在C+中有办法做到这一点吗?

我试着调用类名并使用“this”关键字,但都失败了。


小怪兽爱吃肉
浏览 715回答 3
3回答

湖上湖

不,在C+03中不能从另一个构造函数中调用一个构造函数(称为委托构造函数)。这在C+11(又名C+0x)中发生了变化,增加了对以下语法的支持:(例子取自维基百科)class SomeType{   int number;public:   SomeType(int newNumber) : number(newNumber) {}   SomeType() : SomeType(42) {}};
打开App,查看更多内容
随时随地看视频慕课网APP