说说union

1. 概念

什么是union?
union是一种特殊的类(struct/class),其特殊之处在于,union内的变量共享一段内存,并且union占用内存大小等于其内占用内存最大的变量的大小
eg:

	//定义结构
	struct Node_s
	{
		double a;
		int b;
	};

	//定义union
	union Node_u
	{
		double a;
		int b;
	};

	//输出size
	cout << "size of struct:" << sizeof(Node_s) << endl;
	cout << "size of union:" << sizeof(Node_u) << endl;
输出(vs2010, 32位系统):
size of struct: 16
size of union: 8

2. 应用

union最大的用处在于在某些场景下用来节省内存。
我们常见的一个场景是,有两个变量,但这两个变量我们不会同时需要。
例如,一个人的属性是:姓名、工作类型、工作描述,在描述工作的时候,针对不同的职业,有不同的属性,但是,一个人不会同时拥有两个职业(一般情况下)

code如下:

	//工程师
	struct Engineer 
	{
		int type; //方向
		char company[1024];
	};

	//教师
	struct Teacher 
	{
		int title; // 叫兽,副叫兽?
		int type; //所在专业
		char school[1024]; //学校名称
	};

	//人
	struct Person
	{
		char name[128]; //姓名

		int job_type; //engineer or teacher

		union  Work
		{
			Engineer engineer;
			Teacher teacher;
		}work;
	};

	//输出size
	cout << "size of Engineer:" << sizeof(Engineer) << endl;
	cout << "size of Teacher:" << sizeof(Teacher) << endl;
	cout << "size of Person:" << sizeof(Person) << endl;
输出:
size of Engineer:1028
size of Teacher:1032
size of Person:1164


此处可以用匿名对象,匿名union仅仅通知编译器它的成员变量共享一个地址,而变量本身是直接引用的
eg:

	//工程师
	struct Engineer 
	{
		int type; //方向
		char company[1024];
	};

	//教师
	struct Teacher 
	{
		int title; // 叫兽,副叫兽?
		int type; //所在专业
		char school[1024]; //学校名称
	};

	//人
	struct Person
	{
		char name[128]; //姓名

		int job_type; //engineer or teacher

		union
		{
			Engineer engineer;
			Teacher teacher;
		};
	};
	//匿名对象直接使用
	Person person;
	person.engineer.type = 100;

	//输出size
	cout << "size of Engineer:" << sizeof(Engineer) << endl;
	cout << "size of Teacher:" << sizeof(Teacher) << endl;
	cout << "size of Person:" << sizeof(Person) << endl;


3. 使用注意

如果类是union的成员,则成员类不能提供构造函数、析构函数。这是因为union的成员共享内存,编译器无法保证这些成员在构造时不被破坏,也无法保证离开时调用析够函数。

eg:

	//定义结构
	struct Node_s
	{
		Node_s()
		{
		}
		double a;
		int b;
	};

	//定义union
	union Node_u
	{
		Node_s n_s;
		double a;
		int b;
	};
编译将报错:error C2620: 成员“wmain::Node_u::n_s”(属于联合“wmain::Node_u”)具有用户定义的构造函数或不常用的默认构
但是,如果成员类不提供构造函数,则OK
eg:
	//定义结构
	struct Node_s
	{
		double a;
		int b;
	};

	//定义union
	union Node_u
	{
		Node_s n_s;
		double a;
		int b;
	};

	//输出size
	cout << "size of struct:" << sizeof(Node_s) << endl;
	cout << "size of union:" << sizeof(Node_u) << endl;
输出:
size of struct:16

size of union:16


4. 参考

http://blog.chinaunix.net/space.php?uid=14121858&do=blog&cuid=449785

http://hi.baidu.com/hsyl/blog/item/3a9af91900a43376dbb4bdf0.html/cmtid/94dc8b82ebba7a9ff703a6f2


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值