Overload bracket operators [] to get and set

2020-02-07 17:38发布

I have the following class:

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

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

as you can see I've implemented the square brackets operator for "getting".
Now I would like to implement it for setting, i.e.: risc[1] = 2.

How can it be done?

2条回答
SAY GOODBYE
2楼-- · 2020-02-07 18:20

You need to return a reference from your operator[] so that the user of the class use it for setting the value. So the function signature would be unsigned long& operator [](int i).

查看更多
我想做一个坏孩纸
3楼-- · 2020-02-07 18:34

Try this:

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];}
};
查看更多
登录 后发表回答