Tôi đã có một câu hỏi về một trong các tính năng c ++ 20, các trình khởi tạo được chỉ định (thông tin thêm về tính năng này tại đây )
#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}};
}
Mã này được biên dịch với gcc 9.2.0 và -Wall -Wextra -std=gnu++2acờ.
Như bạn có thể thấy ở trên, cả hai cấu trúc Personvà Employeelà tổng hợp nhưng việc khởi tạo Employeetổng hợp là không thể sử dụng các công cụ khởi tạo được chỉ định.
Ai đó có thể giải thích cho tôi tại sao?
publichoặc privatemọi lúc ... cảm ơn dù sao đi nữa
structs kế thừa công khai theo mặc định
struct Employee : public Person