65

我有以下课程:

class risc { // singleton
    protected:
        static unsigned long registers[8];

    public:
        unsigned long operator [](int i)
        {
            return registers[i];
        }
};

如您所见,我已经为“获取”实现了方括号运算符。
现在我想实现它进行设置,即:risc[1] = 2.

如何做呢?

4

2 回答 2

86

试试这个:

class risc { // singleton
protected:
    static unsigned long registers[8];

public:
    unsigned long operator [](int i) const    {return registers[i];}
    unsigned long & operator [](int i) {return registers[i];}
};
于 2012-06-16T19:57:14.830 回答
14

您需要从您返回一个引用,operator[]以便该类的用户使用它来设置值。所以函数签名是unsigned long& operator [](int i).

于 2012-06-16T19:56:33.153 回答