联合

联合 是用户定义的数据或者仅,在任何给定时间,包含从其对象的类类型列出成员 (虽然对象可以是数组或类类型)。

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

参数

  • tag
    类型名称命名的联合。

  • member-list
    列出该联合能包含数据的类型。 请参见"备注"。

  • declarators
    公告列表指定联合的名称。 有关更多信息,请参见声明概述

备注

联合的 成员列表 一个表示联合可以包含的数据类型。 联合需要足够的存储保留其的最大的成员 成员列表。 更多信息,请参见 联合声明 (C 语言参考)

声明联合

从 UNION 关键字启动联合的声明,并将成员列表中大括号:

// 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()
{
}

使用联合

对. C++ 联合是类类型的一个有限窗体。 它可以包含访问说明符 (公共,从而保护,专用),数据成员和成员函数,包括构造函数和析构函数。 它不能包含虚函数或静态数据成员。 它不能用作基类,也不能具有基类。 成员默认访问联合的是公共的。

对. 联合类型只能包含数据成员。

在 C 中,必须使用 联合 关键字声明联合变量。 在 C++ 中, 联合 关键字不是必需的:

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

联合类型的变量可以个表示联合声明的任何类型的值。 使用成员选择运算符 (.) 访问联合的成员:

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

可以通过将括在大括号的表达式声明和初始化在该语句的一行。 该表达式计算并将其分配给联合的第一个字段。

示例

// 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

NumericType 联合在内存中线 (概念上),如下图所示。

数据存储在 NumericType 联合的成员。

NumericType 联合中的数据存储

请参见

参考

选件类、结构和联合

C++关键字

匿名联合

选件类(C++)

结构(C++)