![](/img/trans.png)
[英]Error: could not convert '<brace-enclosed initializer list>()' from '<brace-enclosed initializer list>' to 'struct'
[英]could not convert {…} from <brace-enclosed initializer list> to struct
我之前使用过TDM-GCC-5.10,现在切换回4.9 MINGW-GCC并尝试使用列表初始化时遇到奇怪的错误:
class Vector2
{
public:
Vector2(float x, float y)
{
this->x = x;
this->y = y;
}
float x = 0.f;
float y = 0.f;
};
struct Test
{
int x = 0;
Vector2 v;
};
int main()
{
Test tst = {0,Vector2(0.0f,0.0f)}; //Error
return 0;
}
错误:
main.cpp: In function 'int main()':
main.cpp:21:41: error: could not convert '{0, Vector2(0.0f, 0.0f)}' from '<brace-enclosed initializer list>' to 'Test'
Test tst = {0,Vector2(0.0f,0.0f)}; //Error
^
我在两个编译器中都使用了C ++ 14。 怎么了?
问题出在这里:
struct Test
{
int x = 0; // <==
Vector2 v;
};
直到最近,默认成员初始化程序阻止该类成为聚合,因此您不能对它们使用聚合初始化。 Gcc 4.9仍然在这里实现旧规则,而gcc 5使用新规则。
你错过了;
在您的类定义之后和在int x = 0
。 然后你得到了很多错误,显然只考虑了最后一个错误。 但是你的编译器很困惑,因为没有定义Vector2
(由于缺少;
)。
这编译:
int main()
{
class Vector2
{
public:
Vector2(float x, float y)
{
this->x = x;
this->y = y;
}
float x = 0.f;
float y = 0.f;
};
struct Test
{
int x;
Vector2 v;
};
Test tst = {0,Vector2(4,5)};
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.