C++联合初始化

Edw*_*d83 2 c++ initialization

我有代码:

class Vector4
{

public:
    union
    {
        float x,y,z,w;
        float v[4];
    };

    Vector4(float _x, float _y, float _z, float _w)
    : x(_x), y(_y), z(_z), w(_w)
    {
        std::cout << "Vector4 constructor: " << this->x << "; " << this->y << "; " << this->z << "; " << this->w << std::endl;
    }
};
Run Code Online (Sandbox Code Playgroud)

我记得在VC 7.1中一切都很好,但在VC 2010中我得到了警告:

警告C4608:'Vector4 :: y'已经被初始化列表中的另一个联盟成员初始化,'Vector4 :::: Vector4 :: x'

当我写:

Vector4 vec(1.0f, 0.0f, 0.0f, 0.0f);
Run Code Online (Sandbox Code Playgroud)

我在控制台中看到:

Vector4构造函数:0; 0; 0; 0

请告诉我,发生了什么?

nne*_*neo 10

你们x,y,z,w彼此联合起来:所有四个浮点数共享相同的内存空间,因为一个联合的每个元素都从相同的内存地址开始.

相反,您希望将所有向量元素放在结构中,如下所示:

union {
    struct { float x, y, z, w; };
    float v[4];
};
Run Code Online (Sandbox Code Playgroud)