2

我正在为我正在研究的 GA 事物组合一个 bitarray 类。我想知道是否有比我想出的更好的方法来让我的 [] 运算符进行分配。现在,我有非常量版本的运算符按值返回一个秘密的“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;
    }
};
4

1 回答 1

2

这是标准方法,称为代理。请注意,它通常在类本身中定义:

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();
    }
};

So that people only get to see the public interface of bit, and cannot conjure up their own.

于 2012-08-24T21:01:46.417 回答