让我们假设我想创建一个带有二进制标志的BitField类和一个构造函数,用于定义其中有多少个标志:BitField bitField(500)
。创建这样一个课程的最佳方法是什么?如果我能读取并在偏移处设置标志并在位域getState(int index) const;
上执行按位操作,那将会很酷。谢谢!
答案 0 :(得分:1)
如果您要求bitset,可以参考STL的实施。
答案 1 :(得分:-3)
以下是我的建议(不包括实施本身):
#include <limits.h>
template<unsigned int SIZE>
class BitField
{
public: //Constructors + Destructor
BitField();
virtual ~BitField();
//-----------------------------------------------------------------------------
public: //Assignment Operators
virtual const BitField& operator=(const BitField& bitField);
virtual const BitField& operator|=(const BitField& bitField);
virtual const BitField& operator&=(const BitField& bitField);
virtual const BitField& operator^=(const BitField& bitField);
virtual const BitField& operator<<=(unsigned int shift);
virtual const BitField& operator>>=(unsigned int shift);
//-----------------------------------------------------------------------------
public: //Unary Operators
virtual BitField operator~() const;
//-----------------------------------------------------------------------------
public: //Binary Operators
friend BitField operator|(const BitField& bitField1,const BitField& bitField2);
friend BitField operator&(const BitField& bitField1,const BitField& bitField2);
friend BitField operator^(const BitField& bitField1,const BitField& bitField2);
virtual BitField operator<<(unsigned int shift) const;
virtual BitField operator>>(unsigned int shift) const;
//-----------------------------------------------------------------------------
public: //Binary Comperators
friend bool operator==(const BitField& bitField1,const BitField& bitField2);
//-----------------------------------------------------------------------------
protected:
unsigned char m_flags[(SIZE-1)/CHAR_BIT+1];
};
注意:使用BitField<500> bitField
而不是BitField bitField(500)
实例化对象。