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 的实例。
问题是您使用的 C++ 编译器根据 C++ 17 标准之前的 C++ 标准来编译您的程序。
\n在 C++ 17 标准之前,聚合不能包含基类。
\n因此,请使用至少设置 C++ 17 标准规范的编译器选项。
\n根据 C++ 14 标准(8.5.1 聚合)
\n\n\n1 聚合是一个数组或类(第 9 条),没有用户提供的\n构造函数 (12.1),没有私有或受保护的非静态数据成员\n(第 11 条),没有基类(第 10 条),并且没有虚函数\n(10.3)。
\n
从 C++ 17 标准开始,聚合允许有基类(11.6.1 聚合)
\n\n\n1 聚合是一个数组或一个类(第 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
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.
That is this program
\nstruct 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}\nRun Code Online (Sandbox Code Playgroud)\nis valid according to the C++ 17 Standard and is invalid according to the C++20 Standard.
\nBut if you will declare the constructor with the specifier explicit
struct B : public A {\n explicit B() = default;\n};\nRun Code Online (Sandbox Code Playgroud)\nthen the program will not be valid even according to the C++ 17 Standard.
\n| 归档时间: |
|
| 查看次数: |
131 次 |
| 最近记录: |