C++联合体的内存使用

联合体占用内存大小是根据其最大元素所需要的内存所决定的,这就意味着,有下面的例子..

#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覆盖了。

原文地址:https://www.cnblogs.com/CAION/p/2825765.html