// File: twodim3.cpp // // Implementation of templated TwoDimArray class. // #ifndef TWODIM_CPP #define TWODIM_CPP #include #include "twodim3.h" using namespace std ; // SmartIntPtr class stuff template SmartPtr::SmartPtr() { p = NULL ; n = 0 ; } template SmartPtr::SmartPtr(T *ptr, unsigned int size) { p = ptr ; // do not allocate memory! n = size ; } template T& SmartPtr::operator[](unsigned int c) { if (c >= n) { cerr << "Out of bounds error in SmartPtr::operator[]\n" ; exit(1) ; } return p[c] ; } // TwoDimArray class // Default constructor, pretty much useless // template TwoDimArray::TwoDimArray() { rows = 0 ; cols = 0 ; M = NULL ; } // Alterante constructor, use this one // template TwoDimArray::TwoDimArray(unsigned int r, unsigned int c) { rows = r ; cols = c ; M = new T[r*c] ; if (M == NULL) { cerr << "Cannot allocate memory in TwoDimArray constructor!\n" ; exit(1) ; } } // Copy Constructor, necessary for classes with dynamic members // template TwoDimArray::TwoDimArray(const TwoDimArray& A) { rows = A.rows ; cols = A.cols ; M = new T[rows*cols] ; if (M == NULL) { cerr << "Cannot allocate memory in TwoDimArray constructor!\n" ; exit(1) ; } for (unsigned int i=0 ; i < rows*cols ; i++) { M[i] = A.M[i] ; } } // Destructor // template TwoDimArray::~TwoDimArray() { delete [] M ; } // Overloaded assignment // template TwoDimArray& TwoDimArray::operator=(const TwoDimArray& rhs) { if (this != &rhs) { // check for self assignment delete [] M ; // free old memory! rows = rhs.rows ; cols = rhs.cols ; M = new T[rows*cols] ; if (M == NULL) { cerr << "Cannot allocate memory in TwoDimArray constructor!\n" ; exit(1) ; } for (unsigned int i=0 ; i < rows*cols ; i++) { M[i] = rhs.M[i] ; } } return *this ; } // Print out // template void TwoDimArray::Print() { for(unsigned int i = 0 ; i < rows * cols ; i++) { // Print newline at end of each row if ( (i > 0) && ( (i % cols) == 0 ) ) { cout << endl ; } cout << M[i] << " " ; } cout << endl ; } // Return int in row r and colum c. // Notes: // 1. Return value is a reference to allow assignment. // 2. row and column indices start at 0, not 1. template T& TwoDimArray::at(unsigned int r, unsigned int c) { if ( r >= rows || c >= cols) { cerr << "Out of bounds error in TwoDimArray::at().\n" ; exit(1) ; } return M[r * cols + c] ; } // Overloaded [] operator returns a SmartIntPtr. // This allows the syntax D[r][c] to be used instead of D.at(r,c). template SmartPtr TwoDimArray::operator[] (unsigned int r) { SmartPtr S(&M[r*cols], cols) ; return S ; } #endif