我正在为我正在处理的 GA 项目构建一个位数组类。我想知道是否有比我想出的更好的方法来让我的 [] 运算符执行任务。现在,我有非常量版本的运算符按值返回 secret “bitsetter”类,这似乎有点过分。我当然不能通过引用返回一点,但我想知道是否有更好的(即更简洁、更高效)的方法。提前致谢。请原谅我的扔0
。完全是一个占位符;)
class bitsetter
{
public:
short ind;
unsigned char *l;
bitsetter & operator=(int val)
{
int vs = 1<<ind;
if( val==0 ) {
vs = ~vs;
*l = *l & vs;
}
else
{
*l = *l | vs;
}
return *this;
}
int value() const
{
return ((*l)>>ind)&1;
}
friend std::ostream & operator << ( std::ostream & out, bitsetter const & b )
{
out << b.value();
return out;
}
operator int () { return value(); }
};
class bitarray
{
public:
unsigned char *bits;
int size;
bitarray(size_t size)
{
this->size = size;
int bsize = (size%8==0)?((size+8)>>3):(size>>3);
bits = new unsigned char[bsize];
for(int i=0; i<size>>3; ++i)
bits[i] = (unsigned char)0;
}
~bitarray()
{
delete [] bits;
}
int operator[](int ind) const
{
if( ind >= 0 && ind < size )
return (bits[ind/8] >> (ind%8))&1;
else
return 0;
}
bitsetter operator[](int ind)
{
if( ind >= 0 && ind < size )
{
bitsetter b;
b.l = &bits[ind/8];
b.ind = ind%8;
return b;
}
else
throw 0;
}
};
最佳答案
这是标准方法,称为代理。请注意,它通常在类本身中定义:
class bitfield
{
public:
class bit
{ };
};
此外,它还更加“安全”:
class bitfield
{
public:
class bit
{
public:
// your public stuff
private:
bit(short ind, unsigned char* l) :
ind(ind), l(l)
{}
short ind;
unsigned char* l;
friend class bitfield;
};
bit operator[](int ind)
{
if (ind >= 0 && ind < size)
{
return bit(&bits[ind/8], ind % 8);
}
else
throw std::out_of_range();
}
};
这样人们只能看到比特的公共(public)接口(interface),而无法想象自己的接口(interface)。
关于c++ - 自定义位数组 [] 和赋值运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12116185/