作为一个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++中调用多个构造函数?

如果这就是你想要的,那不可能。

当然,您可以有多个构造函数,每个构造函数都有唯一的参数签名,然后在实例化一个新对象时调用您想要的那个构造函数。

你甚至可以在构造函数的末尾设置默认参数。

但是你不能有多个构造函数,然后分别调用它们。

如果你想变邪恶,你可以使用“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的解决方案好多了。

在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中,一个构造函数可以调用另一个构造函数重载:

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) {}
};

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