C++ overload operator [ ][ ]
Solution 1:
You cannot overload operator [][]
, but the common idiom here is using a proxy class, i.e. overload operator []
to return an instance of different class which has operator []
overloaded. For example:
class CMatrix {
public:
class CRow {
friend class CMatrix;
public:
int& operator[](int col)
{
return parent.arr[row][col];
}
private:
CRow(CMatrix &parent_, int row_) :
parent(parent_),
row(row_)
{}
CMatrix& parent;
int row;
};
CRow operator[](int row)
{
return CRow(*this, row);
}
private:
int rows, cols;
int **arr;
};
Solution 2:
There is no operator[][]
in C++. However, you can overload operator[]
to return another structure, and in that overload operator[]
too to get the effect you want.