[ fromfile: useroperators.xml id: fncalloperator ]
The function call operator, operator()
is overloadable as a nonstatic member function.
It is more flexible than operator[]
because it can be overloaded with respect to different signatures.
In Example 19.16, there is a multiple-subscript operator for a Matrix
class.
Example 19.16. src/operators/matrix/matrix.h
[ . . . . ] class Matrix { public: Matrix(int rows, int cols); Matrix(const Matrix& mat); ~Matrix(); double& operator()(int i, int j); double operator()(int i, int j) const; // Some useful Matrix operations Matrix& operator=(const Matrix& mat); Matrix operator+(const Matrix& mat) const; Matrix operator*(const Matrix& mat) const; bool operator==(const Matrix& mat) const; int getRows() const; int getCols() const; QString toString() const; private: int m_Rows, m_Cols; double **m_NumArray; //Some refactoring utility functions void sweepClean(); void clone(const Matrix& mat); double rcprod(int row, const Matrix& mat, int col) const; /* Computes dot product of the host's row with mat's col. */ }; [ . . . . ]
Example 19.17. src/operators/matrix/matrix.cpp
[ . . . . ] double Matrix::operator()(int r, int c) const { assert (r >= 0 && r < m_Rows && c >= 0 && c < m_Cols); return m_NumArray[r][c]; } double& Matrix::operator()(int r, int c) { assert (r >= 0 && r < m_Rows && c >= 0 && c < m_Cols); return m_NumArray[r][c]; }
Example 19.18. src/operators/matrix/matrix.cpp
[ . . . . ] Matrix:: Matrix(int rows, int cols):m_Rows(rows), m_Cols(cols) { m_NumArray = new double*[rows]; for (int r = 0; r < rows; ++r) { m_NumArray[r] = new double[cols]; for(int c = 0; c < cols; ++c) m_NumArray[r][c] = 0; } }
Example 19.19. src/operators/matrix/matrix.cpp
[ . . . . ] void Matrix::sweepClean() { for (int r = 0; r < m_Rows; ++r) delete[] m_NumArray[r] ; delete[] m_NumArray; } Matrix::~Matrix() { sweepClean(); }
Generated: 2012-03-02 | © 2012 Alan Ezust and Paul Ezust. |