C++20中的指定初始化器(designated initializers)

指定初始化器(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;
}

执行结果如下图所示:

GitHubhttps://github.com/fengbingchun/Messy_Test

相关推荐
arbboter2 天前
【C++20】新特性探秘:提升现代C++开发效率的利器
c++·c++20·新特性·span·结构化绑定·初始化变量·模板参数推导
猿饵块12 天前
c++20--std::format
c++20
mrbone1123 天前
C++-关于协程的一些思考
开发语言·数据库·c++·c++20·协程·异步·coroutines
xiaolang_8616_wjl1 个月前
c++文字游戏_闯关打怪
开发语言·数据结构·c++·算法·c++20
十年编程老舅1 个月前
跨越十年的C++演进:C++20新特性全解析
c++·c++11·c++20·c++14·c++23·c++17·c++新特性
xiaolang_8616_wjl2 个月前
c++游戏_小恐龙(开源)
开发语言·数据结构·c++·算法·游戏·开源·c++20
a东方青3 个月前
[蓝桥杯C++ 2024 国 B ] 立定跳远(二分)
c++·算法·蓝桥杯·c++20
小葡萄20253 个月前
黑马程序员2024新版C++笔记 第五章 面向对象
开发语言·c++·笔记·c++20
Tipriest_3 个月前
【C++20新特性】ranges::sort()使用方法,优势,注意点
算法·leetcode·c++20·排序·sort
Tipriest_3 个月前
ubuntu20.04&vscode使用C++20(调整gcc版本&vscode设置)
ide·vscode·c++20·gcc