超载支架运营商[]来获取和设置(Overload bracket operators [] to g

2019-06-25 13:38发布

我有以下类:

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

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

你可以看到我已经实现了方括号运算符“渐”。
现在我想实现它用于设定,即: risc[1] = 2

怎么做到呢?

Answer 1:

试试这个:

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


Answer 2:

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



文章来源: Overload bracket operators [] to get and set