初始化聚合联盟

Mac*_*iek 2 c++ const unions

我有一个工会:

union my_union 
{ short int Int16; float Float; };
Run Code Online (Sandbox Code Playgroud)

我想创建:

const my_union u1 = ???;
const my_union u2 = ???;
Run Code Online (Sandbox Code Playgroud)

并将它们的值初始化为不同类型:u1 - > int16 u2 - > float

我怎么做 ?如果无法实现上述目标,是否有任何变通方法?

Dew*_*wfy 10

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;
}
Run Code Online (Sandbox Code Playgroud)

有更复杂的方法来创建类,由union拥有,类必须有一个选择器(使用标量或向量数据类型) - 正确销毁字符串.


Las*_*loG 5

尽管禁止非 POD 成员数据(如上所述),但标准说:

在 8.5.1.15:当联合用大括号封闭的初始化程序初始化时,大括号应仅包含联合的第一个成员的初始化程序。

所以

const my_union u1 = {1};
Run Code Online (Sandbox Code Playgroud)

应该有效,但此表格不能用于第二个(及后续)成员。