构造函数在C++中链接

jsp*_*p99 32 c++ constructor specifications constructor-chaining

我对构造函数链的理解是,当一个类中有多个构造函数(重载的构造函数)时,如果其中一个构造函数试图调用另一个构造函数,那么这个过程称为CON​​STRUCTOR CHAINING,这在C++中是不受支持的.最近我在阅读在线资料时遇到了这一段......就像这样......

您可能会发现自己处于要编写成员函数以将类重新初始化为默认值的情况.因为您可能已经有一个构造函数来执行此操作,您可能会尝试从您的成员函数中调用构造函数.如前所述,链接构造函数调用在C++中是非法的.您可以从函数中的构造函数中复制代码,这将起作用,但会导致重复的代码.在这种情况下,最好的解决方案是将代码从构造函数移动到新函数,并让构造函数调用您的函数来完成初始化数据的工作.

调用构造函数的成员函数是否也在构造函数链接下?请在C++中详细介绍这个主题.

Ser*_*tch 27

C++ 11允许构造函数链接(部分).此功能称为" 委派构造函数 ".所以在C++ 11中你可以做到以下几点

class Foo
{
public:
    Foo(int a) : Foo() { _a = a; }
    Foo(char* b) : Foo() { _b = b; }
    Foo() { _c = 1.5; }
private:
    int _a = 0;
    char* _b = nullptr;
    double _c;
};
Run Code Online (Sandbox Code Playgroud)

但是,有一个严重的限制,即不允许调用另一个构造函数的构造函数初始化任何其他成员.因此,您无法使用委托构造函数执行以下操作:

class Foo
{
public:
    Foo(int a) : Foo(), _a(a) { }
    Foo(char* b) : Foo(), _b(b) { }
    Foo() { _c = 1.5; }
private:
    int _a = 0;
    char* _b = nullptr;
    double _c;
};
Run Code Online (Sandbox Code Playgroud)

对于后一个代码示例,MSVC++ 2013给出编译错误"C3511:对委托构造函数的调用应该是唯一的成员初始化程序".


Arm*_*yan 21

该段基本上说明了这一点:

class X
{
   void Init(params) {/*common initing code here*/ }
   X(params1) { Init(someParams); /*custom code*/ } 
   X(params2) { Init(someOtherParams); /*custom code*/ } 
};
Run Code Online (Sandbox Code Playgroud)

您也不能从成员函数调用构造函数.你可能觉得你已经做到了,但那是一种错觉:

class X
{
public:
    X(int i):i(i){}
    void f()
    {
       X(3); //this just creates a temprorary - doesn't call the ctor on this instance
    }
    int i;
};

int main()
{
    using std::cout;
    X x(4);
    cout << x.i << "\n"; //prints 4
    x.f();
    cout << x.i << "\n"; //prints 4 again
}
Run Code Online (Sandbox Code Playgroud)