c++ - 调用总承包商

标签 c++ constructor

标准定义了三种构造函数:

— 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;
}

demo

例子中的主体是什么?

最佳答案

在你的例子中你有

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/

相关文章:

java - 从父类(super class)调用子类构造函数

python - 如何定义 "operator()"C++ 类方法的 python pybind11 绑定(bind)?

c++ - 如何输出数组表中的横排字母

c++ - 迭代器可以指向特定位置而不是STL集中的值吗?

java - 如何让两个构造函数具有相同数量的参数但在java中用于不同的变量

Java构造函数问题

c# - 构造函数中的虚拟成员调用

构造函数中的php对象缓存

c++ - 在运算符 new 的重载中调用 new 表达式

c++ - OpenGL GLFW 简单立方体不渲染