天天看点

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的值已经丢失了。

继续阅读