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

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

问题描述

我对构造函数链接的理解是,当一个类中有多个构造函数(重载构造函数)时,如果其中一个试图调用另一个构造函数,那么
这个过程称为CON​​STRUCTOR 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.

调用构造函数的成员函数是否也来自构造函数链接?

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

推荐答案

该段落基本上说:

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

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

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