union有两个作用:
1,节约空间,如果一个struct存在两个互斥的变量,则可以把这个struct变成union
2,将同一个内存作为多种解释
代码:
1 #include <iostream> 2 using namespace std; 3 4 //作用1,如果只是存a,20000000 个s_tag节约20M空间 5 union s_tag { int a[100]; 6 char aaa; }; 7 s_tag fa, sa, ua; 8 s_tag multiple(s_tag s) { 9 int j; 10 for(j = 0; j < 100; j++) 11 s.a[j] *= 2; 12 return s; 13 } 14 15 //作用2,将同样一块32位内存解释为int或者分为四块解释为char 16 union bit32_tag{ 17 int whole; 18 struct {char c0, c1, c2, c3; } byte; 19 } v; 20 21 int main() { 22 fa.aaa = 'a'; 23 //for(int j = 0; j < 100; j++) 24 // fa.a[j] = j; 25 for(int j = 0; j < 100; j++) 26 cout << fa.a[j] << endl; 27 cout << "aaa:" << fa.aaa << endl; 28 29 //'A' 30 v.whole = 65; 31 cout << "v.byte.c0: " << v.byte.c0 << endl; 32 cout << "v.byte.c1: " << v.byte.c1 << endl; 33 cout << "v.byte.c2: " << v.byte.c2 << endl; 34 cout << "v.byte.c3: " << v.byte.c3 << endl; 35 36 return 0; 37 }
输出:
97 .. ... .... 0 0 aaa:a v.byte.c0: a v.byte.c1: v.byte.c2: v.byte.c3: