【C / C++】C++20 新特性:Designated Initializer

2023-05-16

C++20 标准引入了 Designated Initializer。它类似 C# 的 Object Initializer 和 Kotlin 的 apply(scope function),允许在仅需要初始化类或结构体的部分成员时,使用更少的代码即可完成。

#include <iostream>

int main() {
	struct point {
		double x = 0, y = 0, z = 0;
	};

	struct line_segment {
		struct point s, t;
	};

	const auto print_point = [](const point& p) {
		std::cout << "<" << p.x << ", " << p.y << ", " << p.z << ">" << std::endl;
	};

	const struct point p{ .x = 1, .y = 2, };
	const struct line_segment s { .s{}, .t{.z = 1} }; // Chained designators are nonstandard in C++. Hence ".t.z = 1" instead of ".t{.z = 1}" will make a Compilation ERROR.
	print_point(p);
	print_point(s.s);
	print_point(s.t);

	return 0;
}

在这里插入图片描述

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

【C / C++】C++20 新特性:Designated Initializer 的相关文章

随机推荐