我认为这是索引运算符。我对吗?
差不多。它被称为下标运算符,它必须接受一个单个参数。您的运营商接受两个,这使您的代码非法。
它支持接下来的事情吗?
假如你有一个正确编写operator []
(不从应用程序的逻辑知道一些背景,我不能告诉你怎么写一个),那么无论是你提到要支持的指令。
然而,为了这个:
a[1] = 3;
是合法的(如果返回一个基本类型),operator []
应该返回一个左参考 - 因此,int&
而不是int
。当然,这意味着左值引用所绑定的对象不能是本地对象或临时对象,因为这意味着返回一个参考。
int& operator [] (const int power) { // <== The function cannot be "const" if you
//^ // are returning a non-const lvalue ref
// to a data member or element of a data
// member array
// here there is some code
}
您可能还需要一个const
版本下标操作的:
int operator [] (const int power) const {
// No need to use a int const& ^^^^^
// here, that is basically the This member function can be const, since it is
// same as returning an int by neither modifying the object on which it is
// value invoked, nor returns any non-const lvalue ref
to a data member or an element of data member
// here there is some code
}
第二个将工作,但所述第一会失败An的方法的例子,因为不必返回一个参考。 – 0x499602D2 2013-04-21 15:24:39
所以我必须定义它:int&operator [](const int power)const; – 2013-04-21 15:27:31
是的,你应该定义返回'int&'的运算符的另一个重载。 – 0x499602D2 2013-04-21 15:28:40