问题描述
我阅读了
但我无法编译给定的示例:
but I can't compile the given example:
union U1 {
int m1;
complex<double> m2; // ok
};
union U2 {
int m1;
string m3; // ok
};
U1 u; // ok
u.m2 = {1,2}; // ok: assign to the complex member
结果:
main.cpp:85:8: error: use of deleted function 'U1::U1()'
U1 u; // ok
^
main.cpp:75:11: note: 'U1::U1()' is implicitly deleted because the default definition would be ill-formed:
union U1 {
^
main.cpp:77:25: error: union member 'U1::m2' with non-trivial 'constexpr std::complex<double>::complex(double, double)'
complex<double> m2; // ok
^
main.cpp:86:5: error: 'u' does not name a type
u.m2 = {1,2}; // ok: assign to the complex member
^
make: *** [main.o] Error 1
问题:
我认为在非限制的联合中,如果没有手动给定默认构造函数,这是真的,如何写一个工作示例?
I thought that in a nonrestricted union the first element will be constructed if no default constructor is manually given. Is this true and how to write a working example?
以下一个也不会编译:
class Y
{
public:
constexpr Y() {}
};
union X
{
int a;
float b;
Y x;
//X(){}
};
X x;
int main(){}
同样的错误信息:
main.cpp:112:7: error: use of deleted function 'X::X()'
X x;
^
main.cpp:104:11: note: 'X::X()' is implicitly deleted because the default definition would be ill-formed:
union X
^
main.cpp:108:11: error: union member 'X::x' with non-trivial 'constexpr Y::Y()'
Y x;
^
make: *** [main.o] Error 1
推荐答案
在标准中,[class.union]在第2段(在注释中)提到:
In the standard, [class.union] mentions in paragraph 2 (in the notes) tells this :
由于您的类没有默认构造函数,所以编译失败。
Since your class has not-default constructor, the compilation fails.
第3段甚至提供了一个例子:
Paragraph 3 even provides an example :
union U {
int i;
float f;
std::strings;
};
并说:
Bjarne写了同样的事情:
Bjarne wrote the same thing :
但示例错误。 std :: string
和 std :: complex
都有非默认构造函数。因此,具有这些要求的工会需要工会的构造函数。
but wrong examples. Both std::string
and std::complex
have non-default constructors. Therefore, unions with those require union's constructor.
这篇关于c ++ 11无限制工会的例子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!