c – 重载括号运算符[]以获取和设置

我有以下课程:

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

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

正如你所看到的,我已经实现了方括号运算符“get”.
现在我想实现它的设置,即:risc [1] = 2.

如何做呢?

解决方法:

尝试这个:

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];}
};
上一篇:python – 快速numpy花式索引


下一篇:python – 使用布尔张量的Tensorflow索引