C++ 中的构造函数继承。派生类的默认构造函数未被调用

Hor*_*ace 2 c++ inheritance constructor c++17

我有这个示例代码:

#include <iostream>

class A
{
public:
    A()
    {
        std::cout << "Default constructor of A" << '\n';
    }
    A(int i)
    {
        std::cout << "Inside the constructor of A with one int argument" << '\n';
    }
};

class B : A
{
    using A::A;
public:
    B()
    {
        std::cout << "Default constructor of B" << '\n';
    }
};


int main()
{
    B b(12);

    std::cout << "End of main";
}

Run Code Online (Sandbox Code Playgroud)

哪个输出:

Inside the constructor of A with one int argument
End of main
Run Code Online (Sandbox Code Playgroud)

我的期望是输出是这样的:

Inside the constructor of A with one int argument
Default constructor of B
End of main
Run Code Online (Sandbox Code Playgroud)

我基于cppreference声明:“如果重载解析在初始化此类派生类的对象时选择继承的构造函数之一,则继承构造函数的 Base 子对象将使用继承的构造函数和所有其他基类进行初始化Derived 的成员就像由默认的默认构造函数一样进行初始化(如果提供,则使用默认成员初始值设定项,否则会发生默认初始化)。整个初始化被视为单个函数调用:继承的构造函数的参数初始化是按顺序进行的- 在派生对象的任何基础或成员初始化之前。”

我是否误读了这个?默认的派生构造函数是否不应该在继承的构造函数之后调用?

for*_*818 7

引用说:

[...] 就像由默认的默认构造函数初始化一样 [...]

默认的默认构造函数是

struct foo {
     foo() = default;
     //        defaulted       because = default;
     // default constrcutor    because can be called without arguments
};
Run Code Online (Sandbox Code Playgroud)

引用解释了成员、基础子对象等是由这样一个默认的默认构造函数“好像”初始化的。引用并没有在任何地方说明实际调用了默认构造函数。此外,您的构造函数不是默认的默认构造函数。它是一个默认的构造函数,但具有自定义实现,即它不是默认的。


PS:要获得您期望的输出,不需要继承构造函数(这是仅在 C++11 中添加的一项功能),但您可以编写:

class B : A
{
public:
    B(int x) : A(x)
    {
        std::cout << "Default constructor of B" << '\n';
    }
};
Run Code Online (Sandbox Code Playgroud)