[英]C++ union initialization
I have the code: 我有代码:
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;
}
};
As I remember in VC 7.1 everything was fine, but in VC 2010 I got warning: 我记得在VC 7.1中一切都很好,但在VC 2010中我得到了警告:
warning C4608: 'Vector4::y' has already been initialized by another union member in the initializer list, 'Vector4::::Vector4::x'
警告C4608:'Vector4 :: y'已经被初始化列表中的另一个联盟成员初始化,'Vector4 :::: Vector4 :: x'
And when I write: 当我写:
Vector4 vec(1.0f, 0.0f, 0.0f, 0.0f);
I see in console: 我在控制台中看到:
Vector4 constructor: 0;
Vector4构造函数:0; 0;
0; 0;
0; 0
0
Please tell me, what happening? 请告诉我,发生了什么?
You unioned x,y,z,w
all to each other: all four floats share the same memory space since every element of a union begins at the same memory address. 你将
x,y,z,w
联合起来:所有四个浮点数共享相同的内存空间,因为一个联合的每个元素都从相同的内存地址开始。
Instead, you want to put all of the vector elements in a struct, like this: 相反,您希望将所有向量元素放在结构中,如下所示:
union {
struct { float x, y, z, w; };
float v[4];
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.