union可以实现多变量共享内存。
例如,下面的结构体Vector4,有时候要用到x,y,z,w表示,有时候要使用数组的下标进行向量或者矩阵的运算。float数组M和x,y,z,w组成的结构体共享内存,x,y,z,w和M数组的元素一一对应,从而实现同一数据类型的两种表达方式。
#include
using namespace std;
struct Vector4
{
union {
float M[4];
struct
{
float x, y, z, w;
};
};
};
int main()
{
Vector4 v;
v.x = v.y = v.z = v.w = 1;
cout << v.x << v.y << v.z << v.w << endl; //输出1111
for(int i = 0; i < 3; i++)
v.M[i] = i;
cout << v.x << v.y << v.z << v.w << endl; //输出0121
return 0;
}
参考资料:《3D游戏编程大师技巧》p230