天天看點

C++ union enum 探究

這兩個關鍵字并不怎麼常用,但是看C++primer plus 面向對象程式設計部分的時候總是能看到類中有用enum定義的變量。是以想弄清楚這兩個關鍵詞到底有什麼用。

首先是UNION,MSDN上的解釋

A union is a user-defined type in which all members share the same memory location.

 This means that at any given time a union can contain no more than one object from its list of members.

It also means that no matter how many members a union has, it always uses only enough memory to store the largest member.

Unions can be useful for conserving memory when you have lots of objects and/or limited memory.

However they require extra care to use correctly because you are responsible for ensuring that you always access the last member that was written to.

If any member types have a non-trivial constructor, then you must write additional code to explicitly construct and destroy that member.

Before using a union, consider whether the problem you are trying to solve could be better expressed by using a base class and derived classes.

C++ union enum 探究

可以看到test1.a的值已經丢失了。

繼續閱讀