我有一个关于 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}};
}
-Wall -Wextra -std=gnu++2a
这段代码是用 gcc 9.2.0 和标志编译的。
正如您在上面看到的,结构Person
和Employee
都是聚合,但是Employee
使用指定的初始化程序无法初始化聚合。
有人可以解释一下为什么吗?