19.9.3. The Function Call operator()

[ fromfile: useroperators.xml id: fncalloperator ]

Example 19.16. src/operators/matrix/matrix.h

[ . . . . ]
class Matrix {
public:
    Matrix(int rows, int cols);                 1
    Matrix(const Matrix& mat);                  2
    ~Matrix();
    double& operator()(int i, int j);
    double operator()(int i, int j) const;
    // Some useful Matrix operations
    Matrix& operator=(const Matrix& mat);       3
    Matrix operator+(const Matrix& mat) const;  4
    Matrix operator*(const Matrix& mat) const;  5
    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();                          6
    void clone(const Matrix& mat);              7
    double rcprod(int row, const Matrix& mat, int col) const; 
                                                /* Computes dot product of the host's row with  mat's col. */
};
[ . . . . ]

1

Allocates and zeros all cells.

2

Copy constructor - clones mat.

3

Deletes host content, clones mat.

4

Matrix addition.

5

Matrix multiplication.

6

Deletes all cells in the host.

7

Makes a copy of the host using new memory.


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();
}