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

輸出相同的值

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