指定初始化器(designated initializers, 指定初始值设定项) 语法如下:C风格指定初始化器语法,初始化数据成员的一种便捷方式
bash
T object = { .des1 = arg1, .des2 { arg2 } ... };
T object { .des1 = arg1, .des2 { arg2 } ... };
说明:
1.每个指示符(designator)必须命名T的直接非静态数据成员 ,并且表达式中使用的所有指示符必须以与T的数据成员相同的顺序出现。
2.使用点运算符(.)后跟成员名称来指定要初始化的成员。
3.禁止收缩转换(narrowing conversion)。
4.每个联合(union)只能提供一个初始化器。
5.指定初始化器列表中未明确列出的任何成员字段均会进行默认初始化。
6.也可用于初始化嵌套的结构或数组(nested structs or arrays),但指示符不能嵌套。
7.不能混合designated and non-designated initialization。
以下为测试代码:
cpp
namespace {
struct A { int x; int y; int z; };
union u { int a; const char* b; };
struct B {
std::string str;
int n = 42;
int m = -1;
};
struct D {
A a;
int m;
int n;
};
} // namespace
int test_designated_initializers()
{
A a{ .x = 1, .z = 2 }; // a.y initialized to 0
std::cout << "value: " << a.x << "," << a.y << "," << a.z << std::endl;
A b = { .y{1}, .z{2} }; // b.x initialized to 0
std::cout << "value: " << b.x << "," << b.y << "," << b.z << std::endl;
//A c{ .y = 2, .x = 1 }; // error; designator order does not match declaration order
u f = { .b = "blog" }; // active member of the union is b
std::cout << "value: " << f.b << std::endl;
B x{ .m = 8 };
std::cout << "value: " << x.str << "," << x.n << "," << x.m << std::endl;
//B y{ .str{"c++20"}, .n{6}, 8 }; // error C7556: 不能将指定初始值设定项与非指定初始值设定项混合
//D t{ .a.x{1} }; // error C7558: 标准C++指定初始值设定项中不允许嵌套的成员访问; 请使用嵌套的初始值设定项列表
D w{ .a{a}, .m{6}, .n{8} };
std::cout << "value: " << w.a.x << "," << w.a.y << "," << w.a.z << "," << w.m << "," << w.n << std::endl;
return 0;
}
执行结果如下图所示: