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);}
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;
Martin york
source share