Освой самостоятельно С++ за 21 день.
Шрифт:
Использование экземпляров шаблона
С экземплярами шаблона можно обращаться так же, как с любыми другими типами данных. Их можно передавать в функции как ссылки или как значения и возвращать как результат выполнения функции (тоже как ссылки или как значения). Способы передачи экземпляров шаблона показаны в листинге 19.5.
Листинг 19.5. Передача в функцию экземпляра шаблона
1: #include <iostream.h>
2:
3: const int DefaultSize = 10;
4:
5: //
6: class Animal
7: {
8: public:
9: // конструкторы
10: Animal(int);
11: Animal;
12: ~Animal;
13:
14: // методы доступа
15: int GetWeight const { return itsWeight; }
16: void SetWeight(int theWeight) { itsWeight = theWeight; }
17:
18: // дружественные операторы
19: friend ostream& operator<< (ostream&, const Animal&);
20:
21: private:
22: int itsWeight;
23: };
24:
25: // оператор вывода объектов типа Animal
26: ostream& operator<<
27: (ostream& theStream, const Animal& theAnimal)
28: {
29: theStream << theAnimal.GetWeight;
30: return theStream;
31: }
32:
33: Animal::Animal(int weight):
34: itsWeight(weight)
35: {
36: // cout << "Animal(int)\n";
37: }
38:
39: Animal::Animal:
40: itsWeight(0)
41: {
42: // cout << "Animal\n";
43: }
44:
45: Animal::~Animal
46: {
47: // cout << "Destroyed an animal...\n";
48: }
49:
50: template <class T> // объявление шаблона и параметра
51: class Array // параметризованный класс
52: {
53: public:
54: Array(int itsSlze = DefaultSize);
55: Array(const Array &rhs);
56: ~Array { delete [] pType; }
57:
56: Array& operator=(const Array&);
59: T& operator[](int offSet) { return pType[offSet]; }
60: const T& operator[](int offSet) const
61: { return pType[offSet]; }
62: int GetSize const { return itsSize; }
63:
64: // функция-друг
65: friend ostream& operator<< (ostream&, const Array<T>&);
66:
67: private:
68: T *рТуре;
69: int itsSize;
70: };
71:
70: template <class T>
72: ostream& operator<< (ostream& output, const Array<T>& theArray)
73: {
74: for (int i = 0; i<theArray.GetSize; i++)
75: output << "[" << i << "] " << theArray[i] << endl;
76: return output;
77: }
78:
79: //
80:
81: // выполнение конструктора
82: template <class T>
83: Array<T>::Array(int size):
84: itsSize(size)
85: {
86: рТуре = new T[size];
67: for (int i = 0; i<size; i++)
88: pType[i] = 0;
89: }
90:
91: // конструктор-копировщик
92: template <class T>
93: Array<T>::Array(const Array &rhs)
94: {
95: itsSize = rhs.GetSize;
96: рТуре = new T[itsSize];
97: for (int i = 0; i<itsSize; i++)
98: pType[i] = rhs[i];
99: }
100:
101: void IntFillFunction(Array<int>& theArray);
102: void AnimalFillFunction(Array<Animal>& theArray);
103:
104: int main
105: {
106: Array<int> intArray;
107: Array<Animal> animalArray;
108: IntFillFunction(intArray);
109: AnimalFillFunction(animalArray);
110: cout << "intArray...\n" << intArray;
111: cout << "\nanimalArray...\n" << aninalArray << endl;
112: return 0;
113: }
114:
115: void IntFillFunction(Array<int>& theArray)
116: {
117: bool Stop = false;
118: int offset, value;
119: while (!Stop)
120: {
121: cout << "Enter an offset (0-9) ";
122: cout << "and a value, (-1 to stop): " ;
123: cin >> offset >> value;
124: if (offset < 0)
125: break;
126: if (offset > 9)
127: {
128: cout << "***Please use values between 0 and 9.***\n";
129: continue;
130: }
131: theArray[offset] = value;
132: }
133: }
134:
135:
136: void AnimalFillFunction(Array<Animal>& theArray)
137: {
138: Animal * pAnimal;
139: for (int i = 0; i<theArray,GetSize; i++)
140: {
141: pAnimal = new Animal;
142: pAnimal->SetWeight(i*100);