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

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

#include 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;
}

在这里插入图片描述


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部