详细解读C++编程中的匿名类类型和位域

2020-01-06 14:35:24王冬梅

数据对象的内容布局
请注意,nYear 的长度为 8 位,并且会溢出声明类型 unsigned short 的字边界。因此,它始于新 unsigned short 的开头。并不必使所有位域均适合基础类型的对象;根据声明中请求的位数来分配新的存储单元。
如果结构的声明包含长度为 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)
};

则内存布局如下图中所示。

详细解读C++编程中的匿名类类型和位域

带有零长度位域的数据对象的布局
位域的基础类型必须是整型类型。



注:相关教程知识阅读请移步到C++教程频道。