zoukankan      html  css  js  c++  java
  • C++位域学习 简单

    Visual Studio 2012 - Visual C++
    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 对象的布局

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

  • 相关阅读:
    windows RabbitMQ Server 环境配置中的一些坑
    Redis自定义fastJson Serializer
    如何使用Feign构造多参数的请求
    跨域访问支持(Spring Boot、Nginx、浏览器)
    chrome浏览器的跨域设置
    Jenkins手把手图文教程[基于Jenkins 2.164.1]
    Spring Boot 2发送邮件手把手图文教程
    poi读取Excel模板并修改模板内容与动态的增加行
    Lock类-ReentrantLock的使用
    类ThreadLocal的使用与源码分析
  • 原文地址:https://www.cnblogs.com/xiangxiaodong/p/2718192.html
Copyright © 2011-2022 走看看