此C ++类需要说明

时间:2017-08-01 16:18:02

标签: c++

我的C ++头文件中有这样的东西

#define CLASS_DECLARATION_S_BIT(Type, FuncName, BitCount)   \
protected:      \
    Type m_k##FuncName : BitCount; \
public:         \
    Type const FuncName()const{return m_k##FuncName;}   \
    void FuncName(Type const& Value){m_k##FuncName = Value;}

typedef struct tagTest
{
public:
    CLASS_DECLARATION_S_BIT(unsigned __int64, Test1, 10);//10
    CLASS_DECLARATION_S_BIT(unsigned __int64, Test2, 7);//17
    unsigned __int64 Test3:4;
    CLASS_DECLARATION_S_BIT(unsigned __int64, Test4, 8);//29
    CLASS_DECLARATION_S_BIT(unsigned __int64, Test5, 4);//33
    CLASS_DECLARATION_S_BIT(unsigned __int64, Test6, 8);//41
    CLASS_DECLARATION_S_BIT(unsigned __int64, Test7, 4);//45
    CLASS_DECLARATION_S_BIT(unsigned __int64, Test8, 8);//53
    CLASS_DECLARATION_S_BIT(unsigned __int64, Test9, 4);//57
    CLASS_DECLARATION_S_BIT(unsigned __int64, Test10, 1);//58
    CLASS_DECLARATION_S_BIT(unsigned __int64, Test11, 1);//59
    CLASS_DECLARATION_S_BIT(unsigned __int64, Test12, 1);//60
    CLASS_DECLARATION_S_BIT(unsigned __int64, Test13, 1);//61
    CLASS_DECLARATION_S_BIT(unsigned __int64, Test14, 1);//62
    CLASS_DECLARATION_S_BIT(unsigned __int64, Test15, 2);//64

    __int64 Field_1()const{return *(((__int64 const*)(this))+0);}
    void Field_1(__int64 const &kValue){*(((__int64*)(this))+0) = kValue;}
}TestInfo;

关于这个的问题,现在Field_1的底部两行是做什么的? 有人可以向我解释一下,谢谢

1 个答案:

答案 0 :(得分:3)

在我看来,这看起来像是一种非常难以进行比特包装的方式。

Field_1()所做的是提供一种方法来访问各个字段的所有值(经过精心设计以适合64位,因此注释)打包到单个int64_t中。

代码滥用了这样一个事实,即压缩字段的内存布局允许它只是重新解释存储在内存中该位置的数据,而不必通过组合各个字段来手动创建值。

它实际上在功能上等同于此(如果我正确地阅读它):

struct tagTest {
  union {
    struct {
      in64_t Test1 : 10;
      in64_t Test2 : 7;
      ...
    };
    int64_t Field_1;
  };
};