C++ 重载括号运算符[]以获取和设置
我有以下课程:C++ 重载括号运算符[]以获取和设置,c++,indexing,overloading,square-bracket,C++,Indexing,Overloading,Square Bracket,我有以下课程: class risc { // singleton protected: static unsigned long registers[8]; public: unsigned long operator [](int i) { return registers[i]; } }; 如您所见,我已经实现了用于“获取”的方括号运算符。 现在我想为设置实现它,即:risc[1]=
class risc { // singleton
protected:
static unsigned long registers[8];
public:
unsigned long operator [](int i)
{
return registers[i];
}
};
如您所见,我已经实现了用于“获取”的方括号运算符。现在我想为设置实现它,即:
risc[1]=2
如何操作?您需要从
操作符[]
返回一个引用,以便类的用户使用它来设置值。因此,函数签名将是无符号长&运算符[](int i)
尝试以下操作:
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];}
};
您还可以返回一个
常量long&
。如果它不是本机类型,则首选这种方式,但对于long
之类的类型,可以按值返回它。。。非常感谢。请注意,最好在i上添加一个测试,以确保它是一个介于0和7之间(包括0和7)的数字。当处理比long复杂得多的类型时,您通常会创建一个引用类(RISCCDATREF),该类保存必要的信息,以便您对主类进行更改。int不应该替换为size_t吗?@Andrew unsigned long operator[](int i)const{return registers[i];}将调用上面的方法吗?我看到另一个函数被调用来获取和设置无符号长&运算符[](inti){返回寄存器[I];}