我对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
使用指定的初始总量是不可能的。
有人可以解释一下为什么吗?
@ skratchi.at stackoverflow.com/a/3965003/11683
—
GSerg
@GSerg好吧,嗯...我从来没有浪费任何想法,因为我每次使用
—
skratchi.at 19/11/15
public
或private
每次...谢谢
您得到的确切错误是什么?
—
skratchi.at
@ skratchi.at
—
idclev 463035818 '19
struct
默认情况下是公开继承的
struct Employee : public Person