说明
C++20 引入了 designated initializers
来使用它们的名字来初始化聚合的数据成员。聚合类型可以是数组类型的对象,或者满足以下限制的结构体或类对象:
- 只有
public
数据成员 - 没有用户声明或继承的构造函数
- 没有虚函数
- 没有
virtual
,private
或protected
基类
例如,对于一个定义如下的员工结构体
struct Employee
{
char firstInitial;
char lastInitial;
int employeeNumber;
int salary { 75'000 };
};
在定义一个结构体对象时,可以使用 uniform initialization
进行初始化,例如:
Employee anEmployee { 'J', 'D', 42, 80'000 };
也可以使用 designated initializers
进行初始化,例如:
Employee anEmployee
{
.firstInitial = 'J',
.lastInitial = 'D',
.employeeNumber = 42,
.salary = 80'000
};
在使用 designated initializers
进行初始化时,也可以初始化部分成员,这样,未被指定初始化的成员则进行 zero initialized
。例如:
Employee anEmployee
{
.firstInitial = 'J',
.lastInitial = 'D',
.salary = 80'000
};
此时,emplyeeNumber
将被设置为 0
.
designated initializers
的优点在于:
- 更容易理解指定的初始化器正在初始化什么
- when members are added to the data structure, existing code using designated initializers keeps working. The new data members will just be initialized with their default values.
实例
#include <iostream>
#include <string>
#include <format>
struct Student
{
std::string name;
int nId;
int nClass;
int nAge;
};
int main()
{
Student a{
.name = "Tom",
.nId = 123456,
.nClass = 3,
.nAge = 20,
};
std::cout << std::format("name: {}, id: {}, class: {}, age: {}\n", a.name, a.nId, a.nClass, a.nAge);
Student b{
.name = "Jerry",
.nId = 123457,
.nAge = 19,
};
std::cout << std::format("name: {}, id: {}, class: {}, age: {}\n", b.name, b.nId, b.nClass, b.nAge);
return 0;
}
程序输出:
name: Tom, id: 123456, class: 3, age: 20
name: Jerry, id: 123457, class: 0, age: 19