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