重载括号运算符[]来获取和设置

时间:2012-06-16 19:54:10

标签: c++ indexing overloading square-bracket

我有以下课程:

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

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

你可以看到我已经实现了“获取”的方括号运算符 现在我想实现它来设置,即:risc[1] = 2

怎么做?

2 个答案:

答案 0 :(得分:65)

试试这个:

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];}
};

答案 1 :(得分:10)

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