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


当前回答

不,在c++中,你不能从构造函数调用构造函数。正如沃伦指出的,你能做的是:

使用不同的签名重载构造函数 在参数上使用默认值,使“更简单”的版本可用

请注意,在第一种情况下,不能通过从一个构造函数调用另一个构造函数来减少代码重复。当然,你可以有一个单独的私有/受保护的方法来完成所有的初始化,让构造函数主要处理参数处理。

其他回答

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

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

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

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

如果你想变邪恶,你可以使用“new”操作符:

class Foo() {
    Foo() { /* default constructor deliciousness */ }
    Foo(Bar myParam) {
      new (this) Foo();
      /* bar your param all night long */
    } 
};

似乎对我有用。

edit

正如@ElvedinHamzagic指出的,如果Foo包含一个分配内存的对象,那么该对象可能不会被释放。这使事情更加复杂。

一个更普遍的例子:

class Foo() {
private:
  std::vector<int> Stuff;
public:
    Foo()
      : Stuff(42)
    {
      /* default constructor deliciousness */
    }

    Foo(Bar myParam)
    {
      this->~Foo();
      new (this) Foo();
      /* bar your param all night long */
    } 
};

看起来确实没那么优雅。@JohnIdol的解决方案好多了。

在c++ 11中,一个构造函数可以调用另一个构造函数重载:

class Foo  {
     int d;         
public:
    Foo  (int i) : d(i) {}
    Foo  () : Foo(42) {} //New to C++11
};

此外,成员也可以这样初始化。

class Foo  {
     int d = 5;         
public:
    Foo  (int i) : d(i) {}
};

这样就不需要创建初始化帮助器方法了。并且仍然建议不要在构造函数或析构函数中调用任何虚函数,以避免使用任何可能未初始化的成员。

在Visual c++中,你也可以在构造函数中使用这个符号:this->Classname::Classname(另一个构造函数的参数)。请看下面的例子:

class Vertex
{
 private:
  int x, y;
 public:
  Vertex(int xCoo, int yCoo): x(xCoo), y(yCoo) {}
  Vertex()
  {
   this->Vertex::Vertex(-1, -1);
  }
};

我不知道它在其他地方是否可以工作,我只在Visual c++ 2003和2008中测试过。我想,您也可以这样调用几个构造函数,就像在Java和c#中一样。

附言:坦率地说,我很惊讶之前没有提到这一点。

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条目以获得参考。