联合体占用内存大小是根据其最大元素所需要的内存所决定的,这就意味着,有下面的例子..
#include <iostream> using namespace std; union test { int k; struct{int x, int y,int z}a; }b; int main() { b.a.x = 1; b.a.y = 2; b.a.z = 3; b.k = 0; cout<<b.a.x<<b.a.y<<b.a.z<<endl; return 0; }
程序的输出结果是 023 ,而不是 123。这是因为,union是共用内存,后来的赋值0将前面的1覆盖了。