我有一个关于C++20特性的问题,即指定初始化器(更多关于这个特性的信息请参见此处)。
#include <iostream>
constexpr unsigned DEFAULT_SALARY {10000};
struct Person
{
std::string name{};
std::string surname{};
unsigned age{};
};
struct Employee : Person
{
unsigned salary{DEFAULT_SALARY};
};
int main()
{
std::cout << std::boolalpha << std::is_aggregate_v<Person> << '\n'; // true is printed
std::cout << std::boolalpha << std::is_aggregate_v<Employee> << '\n'; // true is printed
Person p{.name{"John"}, .surname{"Wick"}, .age{40}}; // it's ok
Employee e1{.name{"John"}, .surname{"Wick"}, .age{40}, .salary{50000}}; // doesn't compile, WHY ?
// For e2 compiler prints a warning "missing initializer for member 'Employee::<anonymous>' [-Wmissing-field-initializers]"
Employee e2 {.salary{55000}};
}
这段代码是使用gcc 9.2.0编译的,并使用了-Wall -Wextra -std=gnu++2a
标志。
正如您在上面看到的那样,Person
和Employee
两个结构体都是聚合体,但是无法使用指定初始化程序来初始化Employee
聚合体。
有人能解释一下为什么吗?
struct Employee : public Person
- skratchi.atpublic
或private
... 不管怎样,还是谢谢。 - skratchi.at