共用體中變量的存儲與名稱無關,只與結構體所在的位置有關;
共用體數據類型將不同類型的數據項存放於同一段內存單元,共用體可以含有不同數據類型的成員,但一次只能處理一個成員。
#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;
}
輸出相同的值