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

Overload bracket operators [] to get and set(重载括号运算符 [] 以获取和设置)

本文介绍了重载括号运算符 [] 以获取和设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下课程:

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

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

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

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.

怎么做?

推荐答案

试试这个:

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

这篇关于重载括号运算符 [] 以获取和设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:重载括号运算符 [] 以获取和设置

基础教程推荐