C++ 重载括号运算符 [] 以获取和设置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11066564/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 14:47:55  来源:igfitidea点击:

Overload bracket operators [] to get and set

c++indexingoverloadingsquare-bracket

提问by SagiLow

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.

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

How can it be done?

怎么做到呢?

回答by Andrew Durward

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

回答by Naveen

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

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