Sams Teach Yourself C++ in 21 Days

(singke) #1
Templates 691

19


84: pType = new T[size];
85: for (int i = 0; i < size; i++)
86: pType[i] = (T)0;
87: itsNumberArrays++;
88: }
89:
90: template <class T>
91: Array<T>& Array<T>::operator=(const Array &rhs)
92: {
93: if (this == &rhs)
94: return *this;
95: delete [] pType;
96: itsSize = rhs.GetSize();
97: pType = new T[itsSize];
98: for (int i = 0; i < itsSize; i++)
99: pType[i] = rhs[i];
100: }
101:
102: template <class T>
103: Array<T>::Array(const Array &rhs)
104: {
105: itsSize = rhs.GetSize();
106: pType = new T[itsSize];
107: for (int i = 0; i < itsSize; i++)
108: pType[i] = rhs[i];
109: itsNumberArrays++;
110: }
111:
112: template <class T>
113: ostream& operator<< (ostream& output, const Array<T>& theArray)
114: {
115: for (int i = 0; i < theArray.GetSize(); i++)
116: output << “[“ << i << “] “ << theArray[i] << endl;
117: return output;
118: }
119:
120: int main()
121: {
122: cout << Array<int>::GetNumberArrays() << “ integer arrays\n”;
123: cout << Array<Animal>::GetNumberArrays();
124: cout << “ animal arrays” << endl << endl;
125: Array<int> intArray;
126: Array<Animal> animalArray;
127:
128: cout << intArray.GetNumberArrays() << “ integer arrays\n”;
129: cout << animalArray.GetNumberArrays();
130: cout << “ animal arrays” << endl << endl;
131:

LISTING19.7 continued

Free download pdf