[英]C++11 POD structure initializing error
我对简单的代码感到困惑:
struct Item {
size_t span{};
};
int main() {
Item item{1}; // error is here
return 0;
}
编译此文件时,出现以下错误:
test.cpp: In function ‘int main()’:
test.cpp:8:13: error: no matching function for call to ‘Item::Item(<brace-enclosed initializer list>)’
Item i{1};
^
test.cpp:8:13: note: candidates are:
test.cpp:3:8: note: constexpr Item::Item()
struct Item {
^
test.cpp:3:8: note: candidate expects 0 arguments, 1 provided
test.cpp:3:8: note: constexpr Item::Item(const Item&)
test.cpp:3:8: note: no known conversion for argument 1 from ‘int’ to ‘const Item&’
test.cpp:3:8: note: constexpr Item::Item(Item&&)
test.cpp:3:8: note: no known conversion for argument 1 from ‘int’ to ‘Item&&’
为什么在这种情况下, g++
尝试为initializer list
找到ctor
而不是创建简单的C样式结构对象?
如果我从size_t span{}
删除{}
,则编译成功。
如果我将行更改为size_t span = 0
,也会发生这种情况,因此似乎是自c ++ 11起存在的声明问题中的一些初始化。
Usign Item item{1};
表示您正在对 (进行item
)的列表初始化 。 列表初始化定义如下:
您的课程没有构造函数。 它也不是(C ++ 11)聚合,因为它包含用于非静态数据成员的初始化程序。
请注意,此限制(成员初始化程序)已在C ++ 14中取消,因此Item
是 C ++ 14的聚合,并且您的代码(虽然无效的C ++ 11)是有效的C ++ 14。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.