摘自cplusplus.com上关于union的解释:
Unions allow one portion of memory to be accessed as different data types. Its declaration and use is similar to the one of structures, but its functionality is totally different:
unions允许一部分内存可以访问不同的数据类型。他的声明和使用和结构体相同,但是他的功能却完全不同。
union type_name { member_type1 member_name1; member_type2 member_name2; member_type3 member_name3; . . } object_names; |
This creates a new union type, identified by type_name
, in which all its member elements occupy the same physical space in memory. The size of this type is the one of the largest member element. For example:
上面定义了一个union类型,由type_name声明,他的数据成员拥有相同的内存空间。这种数据类型的大小和他最大的元素相同,举例来说:
|
|
declares an object (mytypes
) with three members:
声明了一个有三个成员的对象:
|
|
Each of these members is of a different data type. But since all of them are referring to the same location in memory, the modification of one of the members will affect the value of all of them. It is not possible to store different values in them in a way that each is independent of the others.
每个成员都是不同的数据类型。但是由于他们指向相同的内存单元,对他们中任意一个成员的修改都会对其他成员产生影响。
One of the uses of a union is to be able to access a value either in its entirety or as an array or structure of smaller elements. For example:
union的一个用处是他能够以真题或者数组或者结够的形式来访问数据(在这个例子中)。举例来说:
|
|
If we assume that the system where this program runs has an int
type with a size of 4 bytes, and a short
type of 2 bytes, the union defined above allows the access to the same group of 4 bytes: mix.l
, mix.s
and mix.c
, and which we can use according to how we want to access these bytes: as if they were a single value of type int
, or as if they were two values of type short
, or as an array of char
elements, respectively. The example mixes types, arrays, and structures in the union to demonstrate different ways to access the data. For a little-endian system, this union could be represented as:
如果我们假定系统运行int类型4个字节,short类型2个字节,上面定义允许访问4个字节的数组:mix.l,mix.s,mix.c,我们可以按照我们的想法来访问这些字节:分别访问int、short的两个数据、char数组。这个例子混合了类型、数组和结构在union中来说明不同的方法来访问数据。对于小端系统,union可以表示为下面的形式:
The exact alignment and order of the members of a union in memory depends on the system, with the possibility of creating portability issues.
对于不同的系统数据的顺序和对齐可能会不同。
另附一个中文blog,有更详细的代码例子:http://www.jb51.net/article/56009.htm