include <Grid.h> // The file containing the Grid template definition shown above includeinclude using namespace std; template
class GridWIDTH, HEIGHT> { public: Grid(); Grid(const Grid & src); ~Grid(); Grid & Grid ::operator=( const Grid & rhs); void setElementAt(int x, int y, const char* inElem); char* getElementAt(int x, int y) const; int getHeight() const { return HEIGHT; } int getWidth() const { return WIDTH; } protected: void copyFrom(const Grid & src); char* mCells[WIDTH][HEIGHT]; };
templateGrid ::Grid() { for (int i = 0; i < WIDTH; i++) { for (int j = 0; j < HEIGHT; j++) { // initialize each element to NULL mCells[i][j] = NULL; } } } template Grid ::Grid(const Grid & src) { copyFrom(src); } template Grid ::~Grid() { for (int i = 0; i < WIDTH; i++) { for (int j = 0; j < HEIGHT; j++) { delete [] mCells[i][j]; } } } template void Grid ::copyFrom( const Grid & src) { int i, j; for (i = 0; i < WIDTH; i++) { for (j = 0; j < HEIGHT; j++) { if (src.mCells[i][j] == NULL) { mCells[i][j] = NULL; } else { mCells[i][j] = new char[strlen(src.mCells[i][j]) + 1]; strcpy(mCells[i][j], src.mCells[i][j]); } } } } template Grid & Grid ::operator=( const Grid & rhs) { int i, j; // check for self-assignment if (this == &rhs) { return (*this); } // free the old memory for (i = 0; i < WIDTH; i++) { for (j = 0; j < HEIGHT; j++) { delete [] mCells[i][j]; } } // copy the new memory copyFrom(rhs); return (*this); } template void Grid ::setElementAt( int x, int y, const char* inElem) { delete[] mCells[x][y]; if (inElem == NULL) { mCells[x][y] = NULL; } else { mCells[x][y] = new char[strlen(inElem) + 1]; strcpy(mCells[x][y], inElem); } } template char* Grid ::getElementAt(int x, int y) const { if (mCells[x][y] == NULL) { return (NULL); } char* ret = new char[strlen(mCells[x][y]) + 1]; strcpy(ret, mCells[x][y]); return (ret); }
(C) Æliens 20/2/2008
You may not copy or print any of this material without explicit permission of the author or the publisher. In case of other copyright issues, contact the author. </div> <script src="http://www.google-analytics.com/urchin.js" type="text/javascript"> </script> <script type="text/javascript"> _uacct = "UA-2780434-1"; urchinTracker(); </script> </body> </html> <hr> <hr> <table cellpadding=10> <tr> <td> <address> Hush Online Technology </address> hush@cs.vu.nl <br>10/19/08 </td><td>