This question has already been answered:

I have a class "Matrix". And in it you need to overload the operator [] so that when addressing [][] to the elements it makes sense, similarly to the built-in one. I tried this:

 Matrix& operator[][](int a,int b); 

It did not work, Google searches lead nowhere. Maybe someone knows how to implement?

Marked as a duplicate by the participants αλεχολυτ , Harry , VladD c ++ Nov 26 '16 at 20:08 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • one
    Show the declaration of the object to which this statement will apply. - Vlad from Moscow

1 answer 1

Define the operator [] , which will return the string - as a pointer, vector or something else, for which the operator [] defined, which will return a reference to a specific element ...

The simplest example is:

 class Matrix { public: Matrix(int R, int C):R(R),C(C) { d = new int*[R]; for(int i = 0; i < R; ++i) d[i] = new int[C]; } ~Matrix() { for(int i = 0; i < R; ++i) delete[] d[i]; delete[] d; } int* operator[](int idx) { return d[idx]; } const int* operator[](int idx) const { return d[idx]; } private: int ** d; int R, C; }; int main() { Matrix M(3,3); for(int i = 0; i < 3; ++i) for(int j = 0; j < 3; ++j) M[i][j] = 10*i + j; for(int i = 0; i < 3; ++i) { for(int j = 0; j < 3; ++j) { cout << setw(2) << M[i][j] << " "; } cout << endl; } } 

Naturally, no errors are processed by me.