本文介绍了重载括号运算符[]来获取和设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下课程:
class risc { // singleton
protected:
static unsigned long registers[8];
public:
unsigned long operator [](int i)
{
return registers[i];
}
};
你可以看到我已经实现了方括号运算符get。
现在我想实现它的设置,即: 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];}
};
这篇关于重载括号运算符[]来获取和设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!