联合(union)的声明和结构与结构体类似,但是本质不同。
联合的所有成员引用的是内存中的相同位置,当你想在不同时刻把不同的东西存储于同一位置时,就可以使用联合。
构体(struct)中所有变量是“共存”,内存空间的分配是全分配,所有字段的全部和。
联合体(union)中是各变量是“互斥”,内存使用更为精细灵活,也节省了内存空间,字段中取最大的。
struct
指针在x64 占8个字节,在x86占4字节
结构体大小为,每个字段的全部大小和
typedef struct Person{
int age; // 4 byte
float birth; // 4 byte
string name; // 32 byte
}Person;
void test_xhh_01(){
cout << "sizeof(int) = " << sizeof(int) << endl;
cout << "sizeof(float) = " << sizeof(float) << endl;
cout << "sizeof(string) = " << sizeof(string) << endl;
cout << "sizeof(Person) = " << sizeof(Person) << endl;
Person *p1 = new Person;
cout << "sizeof(p1) = " << sizeof(p1) << endl;
cout << "sizeof(*p1) = " << sizeof(*p1) << endl;
}
------------------------------------------------------------
sizeof(int) = 4
sizeof(float) = 4
sizeof(string) = 32
sizeof(Person) = 40
sizeof(p1) = 8
sizeof(*p1) = 40
union
指针在x64 占8个字节
联合体大小为,字段中最大的
成员赋值会相互覆盖,共享同一段首地址
typedef union Student{
int age; // 4 byte
float birth; // 4 byte
string name; // 32 byte
}Student;
void test_xhh_02(){
cout << "sizeof(Student) = " << sizeof(Student) << endl;
Student *s1;
cout << "sizeof(s1) = " << sizeof(s1) << endl;
cout << "sizeof(*s1) = " << sizeof(*s1) << endl;
}
------------------------------------------------------------
sizeof(Student) = 32
sizeof(s1) = 8
sizeof(*s1) = 32
联合使用
typedef struct Person{
int age; // 4 byte
float birth; // 4 byte
string name; // 32 byte
}Person;
typedef struct Student{
int age; // 4 byte
float birth; // 4 byte
string name; // 32 byte
string school; // 32 byte
}Student;
typedef union Common{
Student student; // 40 byte
Person person; // 72 byte
}Common;
void test_xhh_03(){
cout << "sizeof(Person) = " << sizeof(Person) << endl;
cout << "sizeof(Student) = " << sizeof(Student) << endl;
cout << "sizeof(Common) = " << sizeof(Common) << endl;
Person *p1 = new Person;
Student *s1 = new Student;
// 转为通用类型 common 进行中间值传递
Common *c1_from_p1 = (Common*)p1;
Common *c2_from_s1 = (Common*)s1;
// 转为原类型进行使用
// cout << ((Student*)c2_from_s1)->school << endl;
}
------------------------------------------------------------
sizeof(Person) = 40
sizeof(Student) = 72
sizeof(Common) = 72