Sams Teach Yourself C++ in 21 Days

(singke) #1
Templates 671

19


LISTING19.3 Nontemplate Friend Function


0: // Listing 19.3 - Type specific friend functions in templates
1:
2: #include <iostream>
3: using namespace std;
4:
5: const int DefaultSize = 10;
6:
7: // declare a simple Animal class so that we can
8: // create an array of animals
9:
10: class Animal
11: {
12: public:
13: Animal(int);
14: Animal();
15: ~Animal() {}
16: int GetWeight() const { return itsWeight; }
17: void Display() const { cout << itsWeight; }
18: private:
19: int itsWeight;
20: };
21:
22: Animal::Animal(int weight):
23: itsWeight(weight)
24: {}
25:
26: Animal::Animal():
27: itsWeight(0)
28: {}
29:
30: template <class T> // declare the template and the parameter
31: class Array // the class being parameterized
32: {
33: public:
34: // constructors
35: Array(int itsSize = DefaultSize);
36: Array(const Array &rhs);
37: ~Array() { delete [] pType; }
38:
39: // operators
40: Array& operator=(const Array&);
41: T& operator[](int offSet) { return pType[offSet]; }
42: const T& operator[](int offSet) const
43: { return pType[offSet]; }
44: // accessors
45: int GetSize() const { return itsSize; }
46:
47: // friend function
Free download pdf