// The Matrix class demonstrates a lot of important concepts // * Construction of 2-d arrays (data and row pointer arrays) // * Use of dynamic memory to create required arrays // * Use of a destructor to destroy dynamic arrays // * Multiple uses of const, &, and * // * Templated class creation and structure // * Forward declaration of templated class and friend operator<< // Note on & // * When used in a type declaration (parameter list, return // type, it must mean "by reference" // * When applied to an actual variable (eg. int m, n; // int **array = cArray(&m, &n);), it must mean "address of" // Note on * // * Like &, when used in a type declaration, modifies type to // to be a pointer (e.g. int square(int *n);) // * When used with a pointer variable, means dereference // (e.g. int n; square(&n); cout << *n << endl;) #ifndef MATRIX_H #define MATRIX_H #include using namespace std; // Forward declaration of templated class and operator<< as // required by g++ template class Matrix; template ostream& operator<<(ostream& sout, const Matrix &m); template class Matrix { public: // Default constructor creates 0-by-0 matrix Matrix(); // Non-default construtor creates nrow-by-ncol matrix Matrix(int nrow, int ncol); // Copy constructor // Pass-by-reference to prevent copying parameter m // const prevents the function from modifying m Matrix(const Matrix &m); // Matrix destructor ~Matrix(); // Overloaded operator= // Pass-by-reference and return-by reference to prevent // lots of object copying; const prevents the function // from modifying m Matrix& operator=(const Matrix &m); // at(i, j) function - access (i, j) element of matrix // Since at() returns T& (by reference), can be used // to modify elements, e.g. a.at(2,4) = 7; // Note: const prevents changes to class variables, // but allows changes to dynamic arrays T& at(int i, int j) const; // add() function - adds to matrices; returns sum // Pass-by-reference to prevent copying parameter m Matrix add(Matrix &m); // Overloaded operator<< as friend; see forward declaration // Pass-by-reference and return-by-reference since ostream sout // is modified by our function AND may need to be modified // further after it is returned (e.g. cout << a << endl; each // "<<" modifies the ostream cout). // const prevents the function from modifying m // friend allows the function to access class variables friend ostream& operator<< <> (ostream& sout, const Matrix &m); // Extract a C-style array from the Matrix object // Returns an array of pointers to rows as T** // Returns number of rows and columns in nrow and ncol; // nrow and ncol are int* so that the function can // modify their values. T** cArray(int *nrow, int *ncol); private: int m_nrow; // number of rows int m_ncol; // number of columns T **m_rowPtr; // Array of pointers to rows T *m_data; // Data in row-major order }; #include "Matrix.cpp" #endif