#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 }
我认为直接不能超载[] [].
我想我必须间接地做,但如何实现它?
解决方法
更简单的解决方案是使用operator(),因为它允许多个参数.
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;
简单的方法是第一个operator []返回一个中间对象,第二个operator []返回数组中的值.
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;