C语言union关键字

union 维护足够的空间来置放多个数据成员中的“一种”,而不是为每一个数据成员配置空间,在union 中所有的数据成员共用一个空间,同一时间只能储存其中一个数据成员,所有的数据成员具有相同的起始地址。例子如下:
union StateMachine
{
   char character;
   int number;
   char *str;
   double exp;
};

一个union 只配置一个足够大的空间以来容纳最大长度的数据成员,以上例而言,最大长度是double 型态,所以StateMachine 的空间大小就是double 数据类型的大小。

在C++里,union 的成员默认属性页为public。union 主要用来压缩空间。如果一些数据不可能在同一时间同时被用到,则可以使用union。

union UnionT{
	int tempa;
	std::string *tempb;
};
UnionT data;
data.tempa = 1;
data.tempb = new std::string("fasdf");
cout << data.tempa << endl;//1886336
cout << *data.tempb << endl;//fasdf

 证明是共用内存的,设置tempa = 1无效

原文地址:https://www.cnblogs.com/as3lib/p/3922084.html