【发布时间】:2020-03-11 13:08:30
【问题描述】:
我有一个关于 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"}, .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 聚合。
谁能解释一下为什么?
【问题讨论】:
-
不知道能不能解决你的问题,但是你这里可能没有继承public...
struct Employee : public Person -
@skratchi.at stackoverflow.com/a/3965003/11683
-
@GSerg 好的,好吧...我从来没有浪费过这个想法,因为我每次都使用
public或private...谢谢 -
你得到的确切错误是什么??
-
在 SO 上有一个类似的问题。但似乎回答了,为什么它不起作用。 https://stackoverflow.com/questions/23808357/brace-initialization-for-inherited-pod
标签: c++ aggregate c++20 designated-initializer