我正在为我正在做的GA事情组装一个位数组类。我想知道是否有比我想出的更好的方法来让我的[]运算符做赋值。现在,我有一个非常量版本的运算符,它按值返回一个秘密的"bitsetter"类,这似乎有点过分。我当然不能通过引用来返回,但我想知道是否有更好的(即,更简洁、更高效的)方法。提前谢谢。请原谅我的throw 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();
}
};
所以人们只能看到bit的公共界面,而不能变出自己的界面。