c++11中union除了繼承c語言的數據共享內存之外,行爲上越來越像一個類,比如成員默認是public類型。c++11中的新特性:
1、能夠有成員函數,包括構造函數和析構函數
union U //C++11
{
int a;
int b;
char* p;
U() : a(5) {} //ctor with mem init
U(U&& r) { p=r.p; r.p=0;} //move ctor
U&& operator=(U&& r)
{ p=r.p; r.p=0; return *this;} //move assignment op
~U() {delete [] p; } //dtor
}
2、不能繼承,也不能被繼承,也不能有虛函數
class P{};
union U: P {}; //compilation error
class C : public U{}; //also a compilation error
union U //C++11
{
int a;
int b;
char* p;
virtual ~U() {delete [] p; } //compilation error, virtual
};
3、可以有成員變量是類,但是這個類成員不能有自己定義的構造、拷貝、析構、賦值等函數,否則編譯不過(至少在vs2012上是的)
自己定義的構造、拷貝、析構、賦值函數稱爲non-trivial函數,默認的則稱爲trivial函數,相關內容參考鏈接3和4
4、不能有引用成員,不管是左值引用還是右值引用,不能有靜態成員變量,但是可以有靜態成員函數
union U
{
int & r; //compilation error
double && rr; //also a compilation error
};
union U
{
int a;
static void func(){}
};
5、在類的內部使用union,整個類包裝聯合體
class C
{
union //anonymous union
{
int a;
char* p;
};
};
參考鏈接:
http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=556
http://bbs.csdn.net/topics/80436802
http://www.freezhongzi.info/?p=147
http://bbs.csdn.net/topics/110162419