【问题标题】:Defining Bit-Flags Using #define in C++在 C++ 中使用#define 定义位标志
【发布时间】:2011-03-07 01:15:19
【问题描述】:

我正在学习位标志。我已经知道它们是如何工作的以及它们是如何在struct 中定义的。但是,我不确定它们是否可以在 #define 预处理器指令中定义,如下所示:

#define FLAG_FAILED:1

这个预处理器定义指令是struct 位标志定义吗?

PS:我已经遇到过这个相关的问题,但它没有回答我的问题:#defined bitflags and enums - peaceful coexistence in "c"。另外,如果您能指出一些有关预处理器指令的信息,我将不胜感激。

【问题讨论】:

    标签: c++ struct c-preprocessor bit flags


    【解决方案1】:

    您想用来将位标志注入结构的任何#define 必须采用以下形式:

    #define IDENTIFIER SUBSTITUTED_CODE
    

    在您的假设用途中...

    #define FLAG_FAILED:1
    

    标识符中包含冒号,使其无效。

    你可以这样做:

    #define FLAG_FAILED int flag_failed :1
    
    struct X
    {
        char a;
        FLAG_FAILED;
        int b;
        ...
    };
    

    尚不清楚您为什么要考虑对位字段使用定义。如果您只是希望能够改变字段长度,那么:

    #define FLAG_FAILED_BITS 1
    
    struct X
    {
        unsigned flag_failed :FLAG_FAILED_BITS;
    };
    

    ...或...

    #define FLAG_FAILED_BITS :1
    
    struct X
    {
        unsigned flag_failed FLAG_FAILED_BITS;
    };
    

    【讨论】:

    • 简单地说。为什么不能像这样回答所有问题?谢谢你,托尼。
    【解决方案2】:

    #define FLAG_FAILED:1 在大多数人所知的“位标志”的意义上并不是真正的位标志。这也是糟糕的语法。

    位标志通常被定义为你有一个 type 并且你通过“设置”它们来“打开”位。您通过“清除”标志来“关闭”它们。要比较位标志是否打开,请使用所谓的 bitwise 运算符 AND(例如 &)。

    因此,您的 BIT0(例如 2^0)将被定义BIT0 = 0x00000001,而 BIT1(例如 2^1)将被定义为BIT1 = 0x00000002。如果你想坚持使用 define,你可以通过设置和清除来做到这一点:

    #ifndef setBit
    #define setBit(word, mask) word |= mask
    #endif
    
    #ifndef clrBit
    #define clrBit(word, mask) word &= ~mask
    #endif
    

    或作为模板

    template<typename T>
    inline T& setBit(T& word, T mask) { return word |= mask; }
    
    template<typename T>
    inline T& clrBit(T& word, T mask) { return word &= ~mask; }
    

    如果你想设置位,可以这么说,你可以设置如下状态:

    setBit(SystemState, SYSTEM_ONLINE);

    setBit(SystemState, &lt;insert type here&gt;SYSTEM_ONLINE);

    清除将是相同的,只需将 setBit 替换为 clrBit

    要比较,只需这样做:

    if (SystemState & SYSTEM_ONLINE) { ... // do some processing 
    
    }
    

    如果这是在 struct 中,则引用 struct

    【讨论】:

      【解决方案3】:

      使用#define 宏定义位值的形式是:

      #define BIT_ONE    static_cast<int>( 1 << 0 )
      #define BIT_TWO    static_cast<int>( 1 << 1 )
      #define BIT_THREE  static_cast<int>( 1 << 2 )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-27
        相关资源
        最近更新 更多