[英]Struct initialization with {} and ()
When I have a struct当我有一个结构
struct Point
{
int x;
int y;
int z;
}
Why it's possible to write为什么可以写
Point p = {10, 20, 30};
Point p0 {10, 20, 30};
auto p1 = Point{10, 20, 30};
Using {}.使用 {}。 But I can't write with ()但我不能用 () 写
Point p(10,10,10);
auto p1 = Point(10,10,10);
With error有错误
Error C2440 'initializing': cannot convert from 'initializer list' to 'Point '
Since C++20 you can perform aggregate-initialization with parentheses initializer.从 C++20 开始,您可以使用括号初始化程序执行聚合初始化。
T object (arg1, arg2, ...); (5) (since C++20)
Before C++20, Point p(10,10,10);
C++20之前, Point p(10,10,10);
is supposed to call a constructor of Point
taking 3 int
s, but Point
doesn't have such constructor.应该调用Point
的构造函数,采用 3 int
s,但Point
没有这样的构造函数。 As you've showed you have to use braced initializer to perform aggregate-initialization, or provide such a constructor for Point
then you could use both parentheses and braced initializer.正如您所展示的,您必须使用花括号初始化程序来执行聚合初始化,或者为Point
提供这样的构造函数,那么您可以同时使用括号和花括号初始化程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.