共用体(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;
}

输出相同的值

发布了15 篇原创文章 · 获赞 15 · 访问量 979

猜你喜欢

转载自blog.csdn.net/weixin_42204569/article/details/89762752