C++中的构造函数链 [英] Constructor chaining in C++

查看:48
本文介绍了C++中的构造函数链的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对构造函数链的理解是,当一个类中有多个构造函数(重载的构造函数)时,如果其中一个试图调用另一个构造函数,那么此过程称为 CONSTRUCTOR CHAINING ,C++ 不支持该过程.最近我在看网上资料的时候看到了这一段……是这样的……

My understanding of constructor chaining is that , when there are more than one constructors in a class (overloaded constructors) , if one of them tries to call another constructor,then this process is called CONSTRUCTOR CHAINING , which is not supported in C++ . Recently I came across this paragraph while reading online material.... It goes like this ...

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

You may find yourself in the situation where you want to write a member function to re-initialize a class back to default values. Because you probably already have a constructor that does this, you may be tempted to try to call the constructor from your member function. As mentioned, chaining constructor calls are illegal in C++. You could copy the code from the constructor in your function, which would work, but lead to duplicate code. The best solution in this case is to move the code from the constructor to your new function, and have the constructor call your function to do the work of initializing the data.

调用构造函数的成员函数是否也属于构造函数链??请在 C++ 中阐明这个主题.

Does a member function calling the constructor also come under constructor chaining ?? Please throw some light on this topic in C++ .

推荐答案

该段基本上是这样说的:

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
}

这篇关于C++中的构造函数链的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆