为什么union不允许其元素具有用户定义的构造函数?

Roo*_*kie 2 c++ visual-c++ unions c++03

当第一个结构体有构造函数时,如何使第二个结构体工作?我收到错误:

error C2620: member 'test::teststruct::pos' of union 'test::teststruct::<unnamed-tag>' has user-defined constructor or non-trivial default constructor
Run Code Online (Sandbox Code Playgroud)

代码:

struct xyz {
    Uint8 x, y, z, w;
    xyz(Uint8 x, Uint8 y, Uint8 z) : x(x), y(y), z(z) {}
};
struct teststruct {
    union {
        Uint32 value;
        xyz pos; // error at this line.
    };
};
Run Code Online (Sandbox Code Playgroud)

我可以使用一个函数来初始化xyz结构,但它不会慢得多吗?更不用说:我有大量的结构我需要用init_xyz()等前缀创建自己的函数,这是不好的.有没有其他办法解决这个问题?

Sco*_*ham 5

可能要避免这种情况:

struct A {
    Uint8 a;
    A() : a(111) {}
};

struct B {
    Uint8 b;
    B() : b(2222) {}
};

struct teststruct {
    union {
        A aValue;
        B bValue;
    };
};
Run Code Online (Sandbox Code Playgroud)

应该发生什么,A和B构造函数都会尝试以不同的方式初始化相同的内存.可能更容易说不允许使用用户定义的构造函数,而不是让某些规则说明哪些会获胜.