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} };
print_point(p);
print_point(s.s);
print_point(s.t);
return 0;
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/249527c101074d6aad3d030f03114a12.png)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)