It is idiomatic to provide couple of overloads of the operator[]
function – one for const
objects and one for non-const
objects. The return type of the const
member function can be a const&
or just a value depending on the object being returned while the return type of the non-const
member function is usually a reference.
struct Heap{
int H[100];
int operator [] (int i) const {return H[i];}
int& operator [] (int i) {return H[i];}
};
This allows you to modify a non-const
object using the array operator.
Heap h1;
h1[0] = 10;
while still allowing you to access const
objects.
Heap const h2 = h1;
int val = h2[0];