标准定义了三种构造函数:
— delegating constructor
— target constructor
— principal constructor
12.6.2/6:
The principal constructor is the first constructor invoked in the construction of an object (that is, not a target constructor for that object’s construction)
但同一部分说:
Once the target constructor returns, the body of the delegating constructor is executed
因为目标构造函数和委托(delegate)构造函数不能是主构造函数。那么一个是什么?我想通过例子来考虑:
#include <iostream>
using std::cout;
using std::endl;
struct A
{
int a;
A(int a)
{
cout << A::a << endl;
A::a = a;
}
A(int a, int b)
{
cout << A::a << endl;
A::a = a + b;
}
A() : A(10,10)
{
cout << "A()" <<endl;
}
};
A a; //Subsequence of constructor's body execution is A(int, int) --> A()
int main()
{
cout << a.a << endl;
}
例子中的主体是什么?
最佳答案
在你的例子中你有
struct A
{
...
A(int a, int b)
{
...
}
A() : A(10,10) // A() is a delegating constructor and A(int,int) is the target constructor
{
...
}
};
A a;
这意味着 A()
是委托(delegate)构造函数,A(int,int)
是目标构造函数。
标准说 (N3690 §12.6.2 - 6)
The principal constructor is the first constructor invoked in the construction of an object (that is, not a target constructor for that object’s construction).
这意味着 A()
在您的示例中既是委托(delegate)构造函数又是委托(delegate)构造函数,而 A(int,int)
,因为它是由委托(delegate)构造函数调用的,所以它是目标构造函数,它不能是主构造函数。
TL;DR(由 pqnet 建议):
principal -> the one you invoke
delegating -> the one which calls another constructor
target -> the one that is called by another constructor
作为一个不相关的旁注,我同意 Joachim 的观点:您正在默认初始化一个非静态成员变量,并在其初始化之前通过作用域解析打印其值。这是未定义的行为。
关于c++ - 调用总承包商,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25348530/