1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
|
#include <iostream>
struct Vector2
{
float x, y;
Vector2(float x = 0, float y = 0) : x(x), y(y) {}
void Print() const
{
std::cout << "(" << x << ", " << y << ")";
}
};
struct Vector4
{
union
{
/*
* 这两个结构体共享同一个内存,其中Vector
* a对应前两个x, y
* b对应后两个z, w
* 组成为一个Vector,有2个float,另一个struct,有4个float成员
*/
struct
{
float x, y, z, w;
};
struct
{
Vector2 a, b;
};
};
Vector4(float x = 0, float y = 0, float z = 0, float w = 0) : x(x), y(y), z(z), w(w) {}
void Print() const
{
std::cout << "Vector4(" << x << ", " << y << ", " << z << ", " << w << ")";
}
};
void Print(const Vector2& vector2)
{
std::cout << "Vector2: ";
vector2.Print();
std::cout << std::endl;
}
int main()
{
std::cout << "=== Complex Union Example ===" << std::endl;
Vector4 vector4(1.0f, 2.0f, 3.0f, 4.0f);
std::cout << "Original Vector4: ";
vector4.Print();
std::cout << std::endl;
std::cout << "Accessing as individual components:" << std::endl;
std::cout << "x = " << vector4.x << ", y = " << vector4.y
<< ", z = " << vector4.z << ", w = " << vector4.w << std::endl;
std::cout << "Accessing as Vector2 pairs:" << std::endl;
Print(vector4.a); // 前两个分量
Print(vector4.b); // 后两个分量
// 修改Vector2会影响Vector4
vector4.a.x = 10.0f;
vector4.b.y = 20.0f;
std::cout << "After modifying Vector2 components:" << std::endl;
vector4.Print();
std::cout << std::endl;
std::cout << "Size of Vector4: " << sizeof(Vector4) << " bytes" << std::endl;
std::cout << "Size of 4 floats: " << sizeof(float) * 4 << " bytes" << std::endl;
return 0;
}
|