C++ multidimensional array operator
Nope, that is not possible. There are two alternatives, though:
You can have operator[]
return an array of a smaller dimension (For a 3D array, it will return a 2D array, for a 2D array it will return a 1D array, and for a 1D array, it will return a single element). Then you can "string them together" with the syntax you want. (arr[x][y][z]
)
Alternatively, you can overload operator()
, because that can take multiple arguments.
Then you can use it like this, to index into a 3D array for example: arr(x,y,z)
But you can't overload [][]
or [][][]
as a single operator.
Not directly, but you can achieve the same functionality overloading operator[]()
and having it return something that supports operator[]()
itself.
For example:
class A {
std::vector<std::vector<int> > vec;
public:
std::vector<int>& operator[] (int x)
{
return vec[x];
}
};
would allow you to write:
A a;
//...
int y = a[1][2];
because a[1]
returns a std::vector<int>
to which you can apply operator[](2)
.
You need to overload operator[]
and make it return a new class which only has another operator[]
.