union
在C/C++程序的编写中,当多个基本数据类型或复合数据结构要占用同一片内存时,我们要使用联合体;当多种类型,多个对象,多个事物只取其一时(我们姑且通俗地称其为“n 选1”),我们也可以使用联合体来发挥其长处。
vector4 用来表示向量和颜色
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| struct vector4 { union { struct { float r; float g; float b; float a; }; struct { float x; float y; float z; float w; }; }; };
|
1 2 3 4 5 6 7 8 9 10 11 12
| void test() { vector4 v4; v4.x = 1.0f; v4.y = 2.0f; cout << v4.x << " " << v4.y << endl; cout << v4.r << " " << v4.g << endl;
v4.r = 2.0f; v4.g = 1.0f; cout << v4.x << " " << v4.y << endl; cout << v4.r << " " << v4.g << endl; }
|