【C】struct / union

联合(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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值