我有一个工会:
union my_union
{ short int Int16; float Float; };
我想创建:
const my_union u1 = ???;
const my_union u2 = ???;
并将它们的值分别初始化为不同的类型:u1 -> int16 u2 -> float
我怎么做 ?如果上述方法不可行,是否有任何解决方法?
union 可以有任意数量的构造函数-这将适用于没有构造函数的任何数据类型,因此如果排除字符串(或创建指向字符串的指针),您的示例很好
#include <string>
using namespace std;
union my_union
{
my_union(short i16):
Int16(i16){}
my_union(float f):
Float(f){}
my_union(const string *s):
str(s){}
short int Int16; float Float; const string *str;
};
int main()
{
const my_union u1 = (short)5;
const my_union u2 = (float)7.;
static const string refstr= "asdf";
const my_union u3 = &refstr;
}
有更复杂的方法来创建由联合拥有的类,类必须有一个选择器(使用标量或矢量数据类型) - 以正确销毁字符串。
尽管禁止非 POD 成员数据(如上文所述),但标准规定:
在 8.5.1.15:当使用大括号封闭的初始化程序初始化联合时,大括号应仅包含联合的第一个成员的初始化程序。
所以
const my_union u1 = {1};
应该可以,但此表格不能用于第二个(和后续)成员。
联合不能包含字符串等非POD数据类型,所以你的问题没有意义。