作为一个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

所以:)

其他回答

如果我正确理解你的问题,你是在问你是否可以在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) {}
};

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

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

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

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

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

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

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

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

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

简单地说,你不能在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成员,这是有意义的。