struct 与 union 在C与C++中的区别

10 篇文章 0 订阅

在C和C++中 struct 与 union 是非常相似的,只不过 union 共享存储区而已,共享的是数据变量所占空间最大的存储区,其他和struct一样。我举以下例子来说明union在C与C++中的区别
我用的是VS2013编译器
struct与union的区别详解

structunion的区别
1. structunion都是由多个不同的数据类型成员组成, 但在任何同一时刻, union中只存放了一个被选中的成员, 而struct的所有成员都存在。在struct中,各成员都占有自己的内存空间,它们是同时存在的。
2. 一个struct变量的总长度等于所有成员长度之和。在Union中,所有成员不能同时占用它的内存空间,它们不能同时存在。Union变量的长度等于最长的成员的长度。
3. 对于union的不同成员赋值, 将会对其它成员重写, 原来成员的值就不存在了, 而对于struct的不同成员赋值是互不影响的。

一、在C中

//本代码在C中
union Student//定义了一个Student联合体
{
    int a;
    int b;
    char c;
};
int main()
{
    union Student st;//定义Student联合体对象st
    //在C中注意这里定义对象时前要加 union
    st.a = 90;
    printf("st.a= %d\n", st.a);//90
    st.b = 80;
    printf("st.a= %d\n", st.a);//此时st.a(90)已经被st.b(80)覆盖
    printf("st.b= %d\n", st.b);//80

    st.c = '0';//字符0的ASIIC值为48
    printf("st.c= %c\n", st.c);//0
    printf("st.a= %d\n", st.a);//48
    printf("st.b= %d\n", st.b);//48

    st.c = '1';//字符1的ASIIC值为49
    printf("st.c= %c\n", st.c);//1
    printf("st.a= %d\n", st.a);//49
    printf("st.b= %d\n", st.b);//49

    st.c = 'a';//字符a的ASIIC值为97
    printf("st.c= %c\n", st.c);//a
    printf("st.a= %d\n", st.a);//97
    printf("st.b= %d\n", st.b);//97
    system("pause");
    return 0;
}

这里写图片描述

二、在C++中

//在C++中

#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;
union Student
{
    int a;
    int b;
    char c;
};
int main()
{
    Student st;
    st.a = 90;
    cout <<"st.a= "<< st.a <<endl;//90
    st.b = 80;
    cout <<"st.a= "<< st.a <<endl;//此时st.a(90)已经被st.b(80)覆盖
    cout << "st.b= " << st.b << endl;//80

    st.c = '0';//字符0的ASIIC值为48
    cout << "st.c= " << st.c << endl;//0
    cout << "st.a= " << st.a << endl;//48
    cout << "st.b= " << st.b << endl;//48

    st.c = '1';//字符1的ASIIC值为49
    cout << "st.c= " << st.c << endl;//1
    cout << "st.a= " << st.a << endl;//49
    cout << "st.b= " << st.b << endl;//49

    st.c = 'a';//字符a的ASIIC值为97
    cout << "st.c= " << st.c << endl;//a
    cout << "st.a= " << st.a << endl;//97
    cout << "st.b= " << st.b << endl;//97

    Student temp = st;//从中可以看出在C++中union也重载了= 操作符;
    cout << "temp.c= " << temp.c << endl;//a
    cout << "temp.a= " << temp.a << endl;//97
    cout << "temp.b= " << temp.b << endl;//97
    system("pause");
    return 0;
}

这里写图片描述

其他

若你还想了解有关于struct,class等知识请看一下博客:
struct结构在C和C++中的区别
struct 与 class的区别(在标准C++中)

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值