I read http://www.stroustrup.com/C++11FAQ.html#unions http://www.stroustrup.com/C++11FAQ.html#unions
但我无法编译给定的示例:
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
问题:
我认为在非限制联合中,如果没有手动给出默认构造函数,将构造第一个元素。这是真的吗?如何编写一个工作示例?
下面的也不会编译:
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
在标准中,第 2 段(注释中)提到的 [class.union] 告诉我们:
联合体可以有成员函数(包括构造函数和
析构函数),但不是虚拟(10.3)函数。工会不得有
基类。联合不得用作基类。如果有工会
包含引用类型的非静态数据成员的程序是
格式不正确。联合体中至多一个非静态数据成员可以有一个
大括号或等于初始化器。 [注意:如果a的任何非静态数据成员
union 有一个不平凡的默认构造函数(12.1),复制构造函数
(12.8)、移动构造函数 (12.8)、复制赋值运算符 (12.8)、移动
赋值运算符(12.8),或析构函数(12.4),相应的
联合体的成员函数必须由用户提供,否则将被
为联合隐式删除(8.4.3)。 ——尾注]
由于您的类没有默认构造函数,因此编译失败。
第 3 段甚至提供了一个例子:
union U {
int i;
float f;
std::strings;
};
并说 :
由于 std::string (21.3) 声明了所有特殊成员函数的非平凡版本,因此 U 将具有隐式删除的默认构造函数、复制/移动构造函数、复制/移动赋值运算符和析构函数。要使用 U,这些成员函数中的部分或全部必须由用户提供。
Bjarne 写了同样的事情:
如果联合体的成员具有用户定义的构造函数、复制函数或析构函数,则该特殊函数将被删除;也就是说,它不能用于联合类型的对象。这是新的。
但错误的例子。两个都std::string
and std::complex
有非默认构造函数。因此,与这些的联合需要联合的构造函数。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)