Overload bracket operators [] to get and set

我与影子孤独终老i 提交于 2019-11-27 10:25:41

问题


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?


回答1:


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



回答2:


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).



来源:https://stackoverflow.com/questions/11066564/overload-bracket-operators-to-get-and-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!