Operator[][] overload
Is it possible to overload []
operator twice? To allow, something like this: function[3][3]
(like in a two dimensional array).
If it is possible, I would like to see some example code.
You can overload operator[]
to return an object on which you can use operator[]
again to get a result.
class ArrayOfArrays {
public:
ArrayOfArrays() {
_arrayofarrays = new int*[10];
for(int i = 0; i < 10; ++i)
_arrayofarrays[i] = new int[10];
}
class Proxy {
public:
Proxy(int* _array) : _array(_array) { }
int operator[](int index) {
return _array[index];
}
private:
int* _array;
};
Proxy operator[](int index) {
return Proxy(_arrayofarrays[index]);
}
private:
int** _arrayofarrays;
};
Then you can use it like:
ArrayOfArrays aoa;
aoa[3][5];
This is just a simple example, you'd want to add a bunch of bounds checking and stuff, but you get the idea.
For a two dimensional array, specifically, you might get away with a single operator[] overload that returns a pointer to the first element of each row.
Then you can use the built-in indexing operator to access each element within the row.
An expression x[y][z]
requires that x[y]
evaluates to an object d
that supports d[z]
.
This means that x[y]
should be an object with an operator[]
that evaluates to a "proxy object" that also supports an operator[]
.
This is the only way to chain them.
Alternatively, overload operator()
to take multiple arguments, such that you might invoke myObject(x,y)
.