共用体(union)——C语言学习

共用体中变量的存储与名称无关,只与结构体所在的位置有关;

共用体数据类型将不同类型的数据项存放于同一段内存单元,共用体可以含有不同数据类型的成员,但一次只能处理一个成员。

#include<iostream>
using namespace std;
main()
{
	struct student
		{
			int id;//注意这里
			int age;
		};
	struct teacher
		{
			int age;//注意这里
			int id;
		};
	union person
	{
		struct student stu;
		struct teacher tea;

	};
	person per;
	per.stu.id=5;
	per.stu.age=1;
	cout<<"stu "<<per.stu.id<<" "<<per.stu.age<<endl;
	cout<<"tea "<<per.tea.id<<" "<<per.tea.age<<endl;
}

结果按顺序输出

#include<iostream>
using namespace std;
main()
{
	struct student
		{
			int id;
		};
	struct teacher
		{
			int id;
		};
	union person
	{
		struct student stu;
		struct teacher tea;
	};
	person per;
	per.stu.id=5;per.tea.id=1;
	cout<<per.stu.id<<"  "<<per.tea.id<<endl;
	per.stu.id=1;per.tea.id=5;
	cout<<per.stu.id<<"  "<<per.tea.id<<endl;
}

输出相同的值

经验分享 程序员 微信小程序 职场和发展