C++ 位域

类和结构可以包含比整数类型占用更小空间的成员。 这些成员被指定为位域。 位域 member-declarator 规范的语法如下:

declarator  : constant-expression

备注

(可选) declarator 是用来访问程序中成员的名称。 它必须是整型(包括枚举类型)。 constant-expression 指定该成员在框架中占用的位数。 匿名位域,即没有标识符的位域成员可用于填充使用。

备注

宽度为 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 对象的内存布局

请注意 nYear 长度为 8 位和溢出该声明的类型的字边界,无符号的 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 对象的布局

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

请参见

参考

类、结构和联合