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 对象内存布局
请注意 nYear 长度为 8 位并将导致溢出该声明的类型, unsigned short的字边界。因此,它在新 unsigned short的开头开始。不需要的与基础类型的对象所有位域;存储新的单位基于在声明请求的位数分配。
作为位域声明的排序数据是从低到高位,如上面该图所示。
下面一个例子通过匿名的位域强制下一位域的对齐到下一type边界
// 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 对象的内存布局