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


当前回答

另一个还没有展示的选项是将你的类分成两个,在你的原始类周围包装一个轻量级的接口类,以达到你想要的效果:

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

class Test : public Test_Base {
    public Test() : Test_Base() {
    }

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

如果有许多构造函数必须调用它们的“上一级”对应函数,这可能会很混乱,但对于少数构造函数来说,这应该是可行的。

其他回答

c++ 11:是的!

c++ 11及以后的版本也有同样的特性(称为委托构造函数)。

语法与c#略有不同:

class Foo {
public: 
  Foo(char x, int y) {}
  Foo(int y) : Foo('a', y) {}
};

c++ 03:不

不幸的是,在c++ 03中没有办法做到这一点,但是有两种方法来模拟这个:

你可以通过默认参数组合两个(或更多)构造函数: 类Foo { 公众: Foo(char x, int y=0);//结合两个构造函数(char)和(char, int) / /…… }; 使用init方法共享公共代码: 类Foo { 公众: Foo (char x); Foo(char x, int y); / /…… 私人: Void init(char x, int y); }; Foo:: Foo (char x) { Init (x, int(x) + 7); / /…… } Foo::Foo(char x, int y) { init (x, y); / /…… } void Foo::init(char x, int y) { / /…… }

请参阅c++ FAQ条目以获得参考。

我相信你可以从构造函数调用构造函数。它将编译并运行。我最近看到有人这样做,它在Windows和Linux上都可以运行。

它不是你想要的。内部构造函数将构造一个临时的局部对象,该对象在外部构造函数返回时被删除。它们也必须是不同的构造函数,否则你将创建一个递归调用。

裁判:https://isocpp.org/wiki/faq/ctors #初始方法

是或否,取决于c++的版本。

在c++ 03中,不能从一个构造函数调用另一个构造函数(称为委托构造函数)。

这在c++ 11(又名c++ 0x)中改变了,它增加了对以下语法的支持: (例子摘自维基百科)

class SomeType
{
  int number;
 
public:
  SomeType(int newNumber) : number(newNumber) {}
  SomeType() : SomeType(42) {}
};

另一个还没有展示的选项是将你的类分成两个,在你的原始类周围包装一个轻量级的接口类,以达到你想要的效果:

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

class Test : public Test_Base {
    public Test() : Test_Base() {
    }

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

如果有许多构造函数必须调用它们的“上一级”对应函数,这可能会很混乱,但对于少数构造函数来说,这应该是可行的。

简单地说,你不能在c++ 11之前。

c++ 11引入了委托构造函数:

Delegating constructor If the name of the class itself appears as class-or-identifier in the member initializer list, then the list must consist of that one member initializer only; such constructor is known as the delegating constructor, and the constructor selected by the only member of the initializer list is the target constructor In this case, the target constructor is selected by overload resolution and executed first, then the control returns to the delegating constructor and its body is executed. Delegating constructors cannot be recursive. class Foo { public: Foo(char x, int y) {} Foo(int y) : Foo('a', y) {} // Foo(int) delegates to Foo(char,int) };

请注意,委托构造函数是一个全有或全无的提议;如果一个构造函数委托给另一个构造函数,则调用构造函数的初始化列表中不允许有任何其他成员。如果只初始化一次const/reference成员,这是有意义的。