问题描述
我对构造函数链接的理解是,当一个类中有多个构造函数(重载构造函数)时,如果其中一个试图调用另一个构造函数,那么
这个过程称为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,thenthis 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 ...
调用构造函数的成员函数是否也来自构造函数链接?
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 ++中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!