|
|
|
|
|
|
|
There are times, however, when you'll want to keep track of information that is shared among the many objects of a class. For example, you might want to know how many Cats have been born so far, and how many are still in existence. |
|
|
|
|
|
|
|
|
Unlike other member variables, static member variables are shared among all instances of a class. They are a compromise between global data, which is available to all parts of your program, and member data, which is usually available only to each object. |
|
|
|
|
|
|
|
|
You can think of a static member as belonging to the class rather than to the object. Normal member data is one per object, but static members are one per class. Listing 20.1 declares a Cat object with a static data member, HowManyCats. This variable keeps track of how many Cat objects have been created. This is done by incrementing the static variable, HowManyCats, with each construction and decrementing it with each destruction. |
|
|
|
|
|
|
|
|
LISTING 20.1 STATIC MEMBER DATA |
|
|
|
 |
|
|
|
|
1: //Listing 20.1 static data members
2:
3: #include <iostream.h>
4:
5: class Cat
6: {
7: public:
8: Cat(int age = 1):itsAge(age){HowManyCats++; }
9: virtual ~Cat() { HowManyCats-; }
10: virtual int GetAge() const { return itsAge; }
11: virtual void SetAge(int age) { itsAge = age; }
12: static int HowManyCats;
13:
14: private:
15: int itsAge;
16:
17: };
18:
19: int Cat::HowManyCats = 0;
20:
21: int main()
22: {
23: const int MaxCats = 5;
24: Cat *CatHouse[MaxCats]
25: int i;
26: for (i = 0; i<MaxCats; i++)
27: CatHouse[i] = new Cat(i);
28:
29: for (i = 0; i<MaxCats; i++)
30: {
31: cout << There are ; |
|
|
|
 |
|
|
|
|
continues |
|
|
|
|
|