C ++ 20中的指定初始值设定项 [英] Designated initializers in C++20

查看:95
本文介绍了C ++ 20中的指定初始值设定项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对一个c ++ 20功能(指定为初始化程序)有疑问(有关此功能的更多信息此处)

I've got a question about one of the c++20 feature, designated initializers (more info about this feature 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 标志编译的.

This code was compiled with gcc 9.2.0 and -Wall -Wextra -std=gnu++2a flags.

如上所示, Person Employee 这两个结构都是聚合,但是使用指定的初始化程序无法初始化 Employee 聚合

As you can see above, both structs, Person and Employee are aggregates but initialization of Employee aggregate isn't possible using designated initializers.

有人可以解释一下为什么吗?

Could someone explain me why ?

推荐答案

根据C ++ 20标准(9.3.1汇总.第3页)

According to the C++ 20 Standard (9.3.1 Aggregates. p. #3)

(3.1)—如果初始化列表是一个指定的初始化列表,则集合应为类类型,每个标识符中的标识符应命名该类的直接非静态数据成员,并且聚合中显式初始化的元素是是或包含这些成员.

(3.1) — If the initializer list is a designated-initializer-list, the aggregate shall be of class type, the identifier in each designator shall name a direct non-static data member of the class, and the explicitly initialized elements of the aggregate are the elements that are, or contain, those members.

因此,您可能无法使用指定的初始化程序列表来初始化基类的数据成员.

So you may not use the designated initializer list to initialize data members of base classes.

改为使用常用的列表初始化,例如

Use instead the usual list initialization like

Employee e1{ "John", "Wick", 40, 50000 };

Employee e1{ { "John", "Wick", 40 }, 50000 };

@ Jarod42 在您可以写的评论中指出

or as @Jarod42 pointed in a comment you can write

Employee e1{ { .name{"John"}, .surname{"Wick"}, .age{40} }, 50000 };

在这种情况下,直接基类由指定的初始值设定项列表初始化,而Employe类整体由非指定的初始值设定项列表初始化.

In this case the direct base class is initialized by a designated initializer list while the class Employe in whole is initialised by a non-designated initializer list.

这篇关于C ++ 20中的指定初始值设定项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆