2

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

error C2620: member 'test::teststruct::pos' of union 'test::teststruct::<unnamed-tag>' has user-defined constructor or non-trivial default constructor

编码:

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.
    };
};

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

4

2 回答 2

5

可能是为了避免这种情况:

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

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

struct teststruct {
    union {
        A aValue;
        B bValue;
    };
};

应该发生什么,A 和 B 构造函数都将尝试以不同的方式初始化相同的内存。与其有一些规则说哪个会赢,不如说不允许用户定义的构造函数可能更容易。

于 2012-06-20T11:15:08.973 回答
1

来自 C++03,9.5 联合,第 162 页

联合可以具有成员函数(包括构造函数和析构函数),但不能具有虚拟 (10.3) 函数。联合不应有基类。联合不应用作基类。具有非平凡构造函数 (12.1)、非平凡复制构造函数 (12.8)、非平凡析构函数 (12.4) 或非平凡的类的对象复制赋值运算符(13.5.3、12.8)不能是联合的成员,也不能是此类对象的数组

于 2012-06-21T22:36:40.713 回答