子类的列表初始化

Urq*_*art -1 c++ inheritance compiler-errors aggregate list-initialization

我想通过列表初始化来初始化作为 A 子类的类 B ( https://en.cppreference.com/w/cpp/language/list_initialization )

然而,它并不是这样工作的:

struct A {
   int x;
};

struct B : public A {
};

int main()
{
   A a{ 1 }; // compiles
   B b{ 2 }; // doesn't compile
}
Run Code Online (Sandbox Code Playgroud)

有没有办法通过列表初始化来初始化 B 的实例?

本质上,我想在不声明任何构造函数的情况下初始化 B 的实例。

Vla*_*cow 5

问题是您使用的 C++ 编译器根据 C++ 17 标准之前的 C++ 标准来编译您的程序。

\n

在 C++ 17 标准之前,聚合不能包含基类。

\n

因此,请使用至少设置 C++ 17 标准规范的编译器选项。

\n

根据 C++ 14 标准(8.5.1 聚合)

\n
\n

1 聚合是一个数组或类(第 9 条),没有用户提供的\n构造函数 (12.1),没有私有或受保护的非静态数据成员\n(第 11 条),没有基类(第 10 条),并且没有虚函数\n(10.3)。

\n
\n

从 C++ 17 标准开始,聚合允许有基类(11.6.1 聚合)

\n
\n

1 聚合是一个数组或一个类(第 12 条)

\n

(1.1) \xe2\x80\x94 没有用户提供的、显式的或继承的构造函数 (15.1),

\n

(1.2) \xe2\x80\x94 没有私有或受保护的非静态数据成员(第 14 条),

\n

(1.3) \xe2\x80\x94 无虚函数 (13.3),以及

\n

(1.4) \xe2\x80\x94 no virtual, private, or protected base classes (13.1).

\n
\n

Pay also attention to that there is a difference according to aggregates in the C++17 and the C++20 Standards. For example in C++ 17 you are allowed to declare a constructor for an aggregate with the specifier default.

\n

That is this program

\n
struct A {\n   int x;\n};\n\nstruct B : public A {\n    B() = default;\n};\n\nint main()\n{\n   A a{ 1 }; \n   B b{ 2 }; \n}\n
Run Code Online (Sandbox Code Playgroud)\n

is valid according to the C++ 17 Standard and is invalid according to the C++20 Standard.

\n

But if you will declare the constructor with the specifier explicit

\n
struct B : public A {\n   explicit  B() = default;\n};\n
Run Code Online (Sandbox Code Playgroud)\n

then the program will not be valid even according to the C++ 17 Standard.

\n