FAQ 23.09 How can a Matrix-like class have a subscript operator that takes more than one subscript?It should use operator() rather than operator[]. When multiple subscripts are needed, the cleanest approach is to use operator() rather than operator[]. The reason is that operator[] always takes exactly one parameter, but operator() can take any number of parameters. In the case of a rectangular Matrix-like class, an element can be accessed using an (i,j) pair of subscripts. For example, #include <stdexcept> using namespace std; class Matrix { public: double& operator() (unsigned row, unsigned col) throw(out_of_range); double operator() (unsigned row, unsigned col) const throw(out_of_range); private: enum { rows_ = 100, cols_ = 100 }; double data_[rows_ * cols_]; }; inline double& Matrix::operator() (unsigned row, unsigned col) throw(out_of_range) { if (row >= rows_ || col >= cols_) throw out_of_range("Matrix::operator()"); return data_[cols_*row + col]; } inline double Matrix::operator() (unsigned row, unsigned col) const throw(out_of_range) { if (row >= rows_ || col >= cols_) throw out_of_range("Matrix::operator()"); return data_[cols_*row + col]; } To access an element of a Matrix object, users use m(i,j) rather than m[i][j] or m[i,j]: int main() { Matrix m; m(5,8) = 106.15; <-- 1 cout << m(5,8); <-- 2 }
|