例若有以下頭文件(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的,不然必須放在匿名名字空間中。