Sams Teach Yourself C++ in 21 Days

(singke) #1
Templates 689

19


Static Members and Templates ......................................................................


A template can declare static data members. A unique set of static data is created for
each class type that can be created from the template. That is, if you add a static member
to the Arrayclass (for example, a counter of how many arrays have been created), you
have one such member per type: one for all the arrays of Animals and another for all the
arrays of integers. Listing 19.7 adds a static member and a static function to the Array
class.

LISTING19.7 Using Static Member Data and Functions with Templates


0: #include <iostream>
1: using namespace std;
2:
3: const int DefaultSize = 3;
4:
5: // A trivial class for adding to arrays
6: class Animal
7: {
8: public:
9: // constructors
10: Animal(int);
11: Animal();
12: ~Animal();
13:
14: // accessors
15: int GetWeight() const { return itsWeight; }
16: void SetWeight(int theWeight) { itsWeight = theWeight; }
17:
18: // friend operators
19: friend ostream& operator<< (ostream&, const Animal&);
20:
21: private:
22: int itsWeight;
23: };
24:
25: // extraction operator for printing animals
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: {
Free download pdf