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

标签 c++ indexing overloading square-bracket

我有以下类(class):

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

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

如您所见,我已经为“获取”实现了方括号运算符。
现在我想实现它进行设置,即: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];}
};

关于c++ - 重载括号运算符 [] 以获取和设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11066564/

相关文章:

c++ - 内联 assembly 约束修饰符 = 和 +

c++ - 试图从一个类中生成随机 int

c++ - 模板重载加上指向指针的指针

c++ - 重载插入运算符 : no operator found which takes a right-hand operand of type 'unsigned int' (or there is no acceptable conversion)

c++ - 图像处理

c++ - C++中回调矩阵实现的数据结构

sql-server - SQL Server 2008 中是否有外键索引

algorithm - 索引 csv 文件中的列

python - 多维数组上的 numpy 高级索引

vb.net - VB.NET 中的依赖类型