在你的代碼示例中,你正在使用賦值,它要求你返回一個引用。
list[0] = 1;
list.operator[](0) = 1;
int& xref = list.operator[](0);
(xref) = 1; // <-- changed the value of list element 0.
既然你想操作[](INT指數)返回一個值,這將轉化:
int x = list.operator[](0);
x = 1; <-- you changed x, not list[0].
如果你想操作[](INT指數)返回一個值,但也有列表[0] = 1還在工作,你將需要提供操作的兩個版本,以便編譯器能夠確定你想在一個給定的呼叫調用哪個行爲:
// const member, returns a value.
int operator[] (const int index) const {return list[index];}
// non const member, which returns a reference to allow n[i] = x;
int& operator[] (const int index) {return list[index];}
注他們必須分歧呃通過返回類型和成員 - 常量。
#include <iostream>
using namespace std;
class IntList
{
private:
int list[1];
public:
IntList() {list[0] = 0;}
int operator[] (const int index) const { return list[index]; }
int& operator[] (const int index) {return list[index];}
};
int main(int argc, const char** argv)
{
IntList list;
cout << list[0] << endl;
list[0] = 1;
int x = list[0];
cout << list[0] << ", " << x << endl;
return 0;
}
工作演示:http://ideone.com/9UEJND
擺脫& – aaronman
導致列表[0] = 1;有編譯錯誤。 –
這是因爲您正在嘗試分配值 – aaronman