共用方式為


Unions 

A union is a user-defined data or class type that, at any given time, contains only one object from its list of members (although that object can be an array or a class type).

union [tag] { member-list } [declarators];
[union] tag declarators;

Remarks

The member-list of a union represents the kinds of data the union can contain. A union requires enough storage to hold the largest member in its member-list. See Union Declarations (C Language Reference).

Declaring a Union

Begin the declaration of a union with the union keyword, and enclose the member list in curly braces:

// declaring_a_union.cpp
union DATATYPE    // Declare union type
{
    char   ch;
    int    i;
    long   l;
    float  f;
    double d;
} var1;          // Optional declaration of union variable

int main()
{
}

Using a Union

A C++ union is a limited form of the class type. It can contain access specifiers (public, protected, private), member data, and member functions, including constructors and destructors. It cannot contain virtual functions or static data members. It cannot be used as a base class, nor can it have base classes. Default access of members in a union is public.

A C union type can contain only data members.

In C, you must use the union keyword to declare a union variable. In C++, the union keyword is unnecessary:

union DATATYPE var2;   // C declaration of a union variable
DATATYPE var3;         // C++ declaration of a union variable

A variable of a union type can hold one value of any type declared in the union. Use the member-selection operator (.) to access a member of a union:

var1.i = 6;           // Use variable as integer
var2.d = 5.327;       // Use variable as double 

You can declare and initialize a union in the same statement by assigning an expression enclosed in braces. The expression is evaluated and assigned to the first field of the union.

Example

// using_a_union.cpp
#include <stdio.h>

union NumericType
{
    int         iValue;
    long        lValue;  
    double      dValue;  
};

int main()
{
    union NumericType Values = { 10 };   // iValue = 10
    printf_s("%d\n", Values.iValue);
    Values.dValue = 3.1416;
    printf_s("%f\n", Values.dValue);
}

Output

10
3.141600

The NumericType union is arranged in memory (conceptually) as shown in the following figure.

Storage of Data in NumericType Union

Numeric Type Union Data Storage

See Also

Reference

Classes, Structures, and Unions
C++ Keywords
Anonymous Unions
class (C++)
struct (C++)