例若有以下头文件(head.h)ios
//head.h enum color {red,blak,white,blue,yellow}; struct student {char name[6]; int age; int num;}; union score {int i_sc; float f_sc;};
在C中使用的使用的方法函数
#include "head.h" int main(void) { enum color en_col; struct student st_stu; union score un_sc; //.... return 0; }
在C++中使用的使用的方法spa
#include "head.h" int main(void) { color en_col; student st_stu; score un_sc; //.... return 0; }
在C语言中定义这3种变量显得很麻烦,在C中一般使用typedef来达到和C++同样的效果code
//example.c typedef enum _color {red,blak,white,blue,yellow}color; typedef struct _student {char name[6]; int age; int num;}student; typedef union _score {int i_sc; float f_sc;} score; int main(void) { color en_col; student st_stu; score un_sc; //.... return 0; }
下面是一个简单的例子对象
//example2.cpp #include <iostream> using namespace std; struct student { char name[6]; int age; char* GetName(void){return name;}; int GetAge(void){return age;}; };
union score { int i_sc; float f_sc; int GetInt(void){return i_sc;}; float GetFloat(void){return f_sc;}; }; int main(void) { student st_stu = {"Lubin", 27}; score un_sc = {100}; cout << st_stu.GetName() << endl; cout << st_stu.GetAge() << endl; cout << un_sc.GetInt() << endl; return 0; }
/* 输出结果
Lubin
27
100
*/
在C++中struct也是一种类,他与class具备相同的功能,用法彻底相同。blog
惟一的区别就是:在没有指定成员的访问权限时,struct中默认为public权限,class中默认为private权限。继承
union能够定义本身的函数,包括 constructor 以及 destructor。
union支持 public , protected 以及 private 权限。内存
读者看到这可能会问,要是这样的话,union与class还有什么区别吗?区别固然仍是有的编译器
1. union不支持继承。也就是说,union既不能有父类,也不能做为别人的父类。it
2. union中不能定义虚函数。
3.在没有指定成员的访问权限时,union中默认为public权限
4.union中的成员类型比class少,具体见2.2.1节
联合里面的东西共享内存,因此静态、引用都不能用,由于他们不可能共享内存。
不是全部类都能做为union的成员变量,若是一个类,包括其父类,含有自定义的constructor,copy constructor,destructor,copy assignment operator(拷贝赋值运算符), virtual function中的任意一个,
那么这种类型的变量不能做为union的成员变量,由于他们共享内存,编译器没法保证这些对象不被破坏,也没法保证离开时调用析够函数。
若是咱们在定义union的时候没有定义名字,那么这个union被称为匿名union(anonymous union)。
匿名联合仅仅通知编译器它的成员变量共同享一个地址,而且变量自己是直接引用的,不使用一般的点号运算符语法.
匿名union的特色以下:
1. 匿名union中不能定义static变量。2. 匿名union中不能定义函数。3. 匿名union中不支持 protected 以及 private 权限。4. 在全局域以及namespace中定义的匿名union只能是static的,不然必须放在匿名名字空间中。