// listing 19.2 The implementation of the template array #include using namespace std; const int DEFAULT_SIZE = 10; // declare a simple Animal class so that we can create an array of animals class Animal { public: Animal(int); Animal(); ~Animal(){} int getWeight() const { return itsWeight; } void display() const { cout << itsWeight; } private: int itsWeight; }; Animal::Animal(int weight):itsWeight(weight) {} Animal::Animal():itsWeight(0) {} // *************************************************************************** template // declare the template and the parameter class Array // the class being parameterized { public: Array(int itsSize = DEFAULT_SIZE); Array(const Array &rhs); ~Array() { delete [] pType; } Array& operator=(const Array&); T& operator[](int offSet) { return pType[offSet]; } const T& operator[](int offSet) const { return pType[offSet]; } int getSize() const { return itsSize; } private: T *pType; int itsSize; }; // implement the Constructor template Array::Array(int size = DEFAULT_SIZE):itsSize(size) { pType = new T[size]; for (int i = 0; i < size; i++) { pType[i] = 0; } } // copy constructor template Array::Array(const Array &rhs) { itsSize = rhs.getSize(); pType = new T[itsSize]; for (int i = 0; i < itsSize; i++) { pType[i] = rhs[i]; } } // operator= template Array& Array::operator=(const Array &rhs) { if (this == &rhs) { return *this; } delete [] pType; itsSize = rhs.getSize(); pType = new T[itsSize]; for (int i = 0; i < itsSize; i++) { pType[i] = rhs[i]; } return *this; } // ******************************************************************* int main() { Array theArray; // an array of integers Array theZoo; // an array of Animals Animal *pAnimal; // fill the arrays for (int i = 0; i < theArray.getSize(); i++) { theArray[i] = i * 2; pAnimal = new Animal(i * 3); theZoo[i] = *pAnimal; delete pAnimal; } // print the contents of the arrays int j = 0; for (j = 0; j < theArray.getSize(); j++) { cout << "theArray[" << j << "]:\t"; cout << theArray[j] << "\t\t"; cout << "theZoo[" << j << "]:\t"; theZoo[j].display(); cout << endl; } for (int k = 0; k < theArray.getSize(); k++) { delete &theZoo[k]; } return 0; }