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

输出相同的值

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章