Structure initialization error: could not convert from ‘<brace-enclosed initializer list>’ to structure
Structure initialization error: could not convert from ‘<brace-enclosed initializer list>’ to structure
我有以下代码:
struct Vec { double x=0, y=0, z=0; };
Vec orig = {1,2,3};
GCC 4.8.4 显示以下错误:
error: could not convert ‘{1, 2, 3}’ from ‘<brace-enclosed initializer list>’ to ‘Vec’
Vec orig = {1,2,3};
^
我改的时候去掉等号
Vec orig {1,2,3};
出现另一个错误:
error: no matching function for call to ‘Vec::Vec(<brace-enclosed initializer list>)’
Vec orig {1,2,3};
^
如何在不创建构造函数的情况下正确初始化结构?
看起来您正在使用 c++11,但还不是 c++14。
一旦你提供了默认成员初始值设定项,class就不再是聚合,你就不能使用聚合初始化.
https://en.cppreference.com/w/cpp/language/aggregate_initialization
An aggregate is one of the following types:
...
class type (typically, struct or union), that has
...
- no default member initializers (until c++14)
我有以下代码:
struct Vec { double x=0, y=0, z=0; };
Vec orig = {1,2,3};
GCC 4.8.4 显示以下错误:
error: could not convert ‘{1, 2, 3}’ from ‘<brace-enclosed initializer list>’ to ‘Vec’
Vec orig = {1,2,3};
^
我改的时候去掉等号
Vec orig {1,2,3};
出现另一个错误:
error: no matching function for call to ‘Vec::Vec(<brace-enclosed initializer list>)’
Vec orig {1,2,3};
^
如何在不创建构造函数的情况下正确初始化结构?
看起来您正在使用 c++11,但还不是 c++14。
一旦你提供了默认成员初始值设定项,class就不再是聚合,你就不能使用聚合初始化.
https://en.cppreference.com/w/cpp/language/aggregate_initialization
An aggregate is one of the following types:
...
class type (typically, struct or union), that has
...
- no default member initializers (until c++14)