且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C++中的构造函数链

更新时间:2022-06-15 09:51:56

该段基本上是这样说的:

The paragraph basically says this:

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

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

You cannot call a constructor from a member function either. It may seem to you that you've done it, but that's an illusion:

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 << "
"; //prints 4
    x.f();
    cout << x.i << "
"; //prints 4 again
}