C++位域

类和结构可以包含比整型占用小于存储的成员。 这些成员指定为位域。 位域 成员声明 规范的语法如下:

declarator  : constant-expression

备注

(可选) declarator 是该成员在程序捕获的名称。 它必须是整型 (包括枚举类型)。 常数表达式 指定该成员在结构占用的位数。 匿名位域,即不标识符的位域成员 )可用于填充使用。

备注

宽度为 0 的一个未命名的位域强制下一位域的对齐到下一 type 边界, type 是该成员的类型。

下面的示例声明一位域的机制:

// bit_fields1.cpp
// compile with: /LD
struct Date {
   unsigned short nWeekDay  : 3;    // 0..7   (3 bits)
   unsigned short nMonthDay : 6;    // 0..31  (6 bits)
   unsigned short nMonth    : 5;    // 0..12  (5 bits)
   unsigned short nYear     : 8;    // 0..100 (8 bits)
};

类型 Date 对象的概念内存布局如下图所示。

date 对象内存布局

Date 对象内存布局图

请注意 nYear 长度为 8 位并将导致溢出该声明的类型, unsigned short的字边界。 因此,它在新 unsigned short的开头开始。 不需要的与基础类型的对象所有位域;存储新的单位基于在声明请求的位数分配,。

Microsoft 专用

作为位域声明的排序数据是从低到高位,如上面该图所示。

特定于 Microsoft 的结尾

如下面的示例所示,如果结构的声明包括长度为 0 的一个未命名的字段,,

// bit_fields2.cpp
// compile with: /LD
struct Date {
   unsigned nWeekDay  : 3;    // 0..7   (3 bits)
   unsigned nMonthDay : 6;    // 0..31  (6 bits)
   unsigned           : 0;    // Force alignment to next boundary.
   unsigned nMonth    : 5;    // 0..12  (5 bits)
   unsigned nYear     : 8;    // 0..100 (8 bits)
};

如下图所示,内存布局是。

date 对象布局与零的位域的

0 长度位字段的 Date 对象的布局

位域的基础类型必须是整型,如 基础类型所述。

请参见

参考

选件类、结构和联合