我对一个c ++ 20功能(指定为初始化程序)有疑问(有关此功能的更多信息here)
#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"},.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
聚合的初始化无法使用指定的初始化程序进行。
有人可以解释一下为什么吗?