Sams Teach Yourself C++ in 21 Days

(singke) #1
Templates 667

19


67: itsSize = rhs.GetSize();
68: pType = new T[itsSize];
69: for (int i = 0; i<itsSize; i++)
70: pType[i] = rhs[i];
71: }
72:
73: // operator=
74: template <class T>
75: Array<T>& Array<T>::operator=(const Array &rhs)
76: {
77: if (this == &rhs)
78: return *this;
79: delete [] pType;
80: itsSize = rhs.GetSize();
81: pType = new T[itsSize];
82: for (int i = 0; i<itsSize; i++)
83: pType[i] = rhs[i];
84: return *this;
85: }
86:
87: // driver program
88: int main()
89: {
90: Array<int> theArray; // an array of integers
91: Array<Animal> theZoo; // an array of Animals
92: Animal *pAnimal;
93:
94: // fill the arrays
95: for (int i = 0; i < theArray.GetSize(); i++)
96: {
97: theArray[i] = i*2;
98: pAnimal = new Animal(i*3);
99: theZoo[i] = *pAnimal;
100: delete pAnimal;
101: }
102: // print the contents of the arrays
103: for (int j = 0; j < theArray.GetSize(); j++)
104: {
105: std::cout << “theArray[“ << j << “]:\t”;
106: std::cout << theArray[j] << “\t\t”;
107: std::cout << “theZoo[“ << j << “]:\t”;
108: theZoo[j].Display();
109: std::cout << std::endl;
110: }
111:
112: return 0;
113: }

LISTING19.2 continued

Free download pdf