转载自: https://blog.csdn.net/mm_hh/article/details/70469573
在C和C++中 struct 与 union 是非常相似的,只不过 union 共享存储区而已,共享的是数据变量所占空间最大的存储区,其他和struct一样。我举以下例子来说明union在C与C++中的区别:
我用的是VS2013编译器
struct与union的区别
1. struct和union都是由多个不同的数据类型成员组成, 但在任何同一时刻, 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;
}