コード例では、参照を返す必要がある代入を使用しています。
list[0] = 1;
list.operator[](0) = 1;
int& xref = list.operator[](0);
(xref) = 1; // <-- changed the value of list element 0.
operator[](int index) が値を返すようにしたい場合、これは次のように変換されます。
int x = list.operator[](0);
x = 1; <-- you changed x, not list[0].
operator[](int index) で値を返すだけでなく、list[0] = 1 も機能するようにする場合は、2 つのバージョンの演算子を提供して、コンパイラがどちらの動作を試みているかを判断できるようにする必要があります。特定の呼び出しで呼び出すには:
// 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