You overload operator[] with a nonstatic member function that has only one parameter. The following example is a simple array class that has an overloaded subscripting operator. The overloaded subscripting operator throws an exception if you try to access the array outside of its specified bounds:
#include <iostream>
using namespace std;
template <class T> class MyArray {
private:
T* storage;
int size;
public:
MyArray(int arg = 10) {
storage = new T[arg];
size = arg;
}
~MyArray() {
delete[] storage;
storage = 0;
}
T& operator[](const int location) throw (const char *);
};
template <class T> T& MyArray<T>::operator[](const int location)
throw (const char *) {
if (location < 0 || location >= size) throw "Invalid array access";
else return storage[location];
}
int main() {
try {
MyArray<int> x(13);
x[0] = 45;
x[1] = 2435;
cout << x[0] << endl;
cout << x[1] << endl;
x[13] = 84;
}
catch (const char* e) {
cout << e << endl;
}
}
The following is the output of the above example:
45
2435
Invalid array access
The expression x[1] is interpreted as x.operator[](1) and calls int& MyArray<int>::operator[](const int).
Related information