How to overload an array index operator for a wrapper class of a 2D class?

#define ROW 3 #define COL 4 class Matrix { private: int mat[ROW][COL]; //..... //..... }; int main() { Matrix m; int a = m[0][1]; // reading m[0][2] = m[1][1]; // writing } 

I think it’s directly impossible to overload [] [].

I think I should do it indirectly, but how to implement it?

+6
c ++ operator-overloading
source share
2 answers

A simpler solution is to use the () operator, since it allows several parameters.

 class M { public: int& operator()(int x,int y) {return at(x,y);} // .. Stuff to hold data and implement at() }; M a; a(1,2) = 4; 

A simple way is that the first operator [] returns an intermediate object, which the second operator [] returns a value from the array.

 class M { public: class R { private: friend class M; // Only M can create these objects. R(M& parent,int row): m_parent(parent),m_row(row) {} public: int& operator[](int col) {return m_parent.at(m_row,col);} private: M& m_parent; int m_row; }; R operator[](int row) {return R(*this,row);} // .. Stuff to hold data and implement at() }; M b; b[1][2] = 3; // This is shorthand for: R row = b[1]; int& val = row[2]; val = 3; 
+10
source share

Since you want to store your elements in fixed-size arrays, this will be pretty simple:

 #define ROWS 3 #define COLS 4 typedef int row_type[COLS]; class matrix { row_type elements[ROWS]; public: ... row_type const& operator[](int r) const {return elements[r];} row_type & operator[](int r) {return elements[r];} ... }; 

That should work.

Alternatively, you can replace #define with the correct constants or use the template options for type (int) and size (3x4) to make your matrix class more general. If you want to support dynamic sizes, your operator [] needs to return proxy objects. This is possible, but you should probably prefer operator () with two index parameters to access the element.

+1
source share

All Articles