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


当前回答

测试比决定更容易:) 试试这个:

#include <iostream>

class A {
public:
    A( int a) : m_a(a) {
        std::cout << "A::Ctor" << std::endl;    
    }
    ~A() {
        std::cout << "A::dtor" << std::endl;    
    }
public:
    int m_a;
};

class B : public A {
public:
    B( int a, int b) : m_b(b), A(a) {}
public:
    int m_b;
};

int main() {
    B b(9, 6);
    std::cout << "Test constructor delegation a = " << b.m_a << "; b = " << b.m_b << std::endl;    
    return 0;
}

然后用98 std编译: g++ main.cpp -std=c++98 -o test_1

你会看到:

A::Ctor
Test constructor delegation a = 9; b = 6
A::dtor

所以:)

其他回答

测试比决定更容易:) 试试这个:

#include <iostream>

class A {
public:
    A( int a) : m_a(a) {
        std::cout << "A::Ctor" << std::endl;    
    }
    ~A() {
        std::cout << "A::dtor" << std::endl;    
    }
public:
    int m_a;
};

class B : public A {
public:
    B( int a, int b) : m_b(b), A(a) {}
public:
    int m_b;
};

int main() {
    B b(9, 6);
    std::cout << "Test constructor delegation a = " << b.m_a << "; b = " << b.m_b << std::endl;    
    return 0;
}

然后用98 std编译: g++ main.cpp -std=c++98 -o test_1

你会看到:

A::Ctor
Test constructor delegation a = 9; b = 6
A::dtor

所以:)

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

这种方法可能适用于某些类型的类(当赋值操作符表现“良好”时):

Foo::Foo()
{
    // do what every Foo is needing
    ...
}

Foo::Foo(char x)
{
    *this = Foo();

    // do the special things for a Foo with char
    ...
}

如果我正确理解你的问题,你是在问你是否可以在c++中调用多个构造函数?

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

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

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

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

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

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

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