|
|
 |
|
|
|
|
26: int i;
27: for (i = 0; i<MaxCats; i++)
28: {
29: CatHouse[i] = new Cat(i);
30: TelepathicFunction();
31: }
32:
33: for ( i = 0; i<MaxCats; i++)
34: {
35: delete CatHouse[i];
36: TelepathicFunction();
37: }
38: return 0;
39: }
40:
41: void TelepathicFunction()
42: {
43: cout << There are << Cat::GetHowMany() << cats alive!\n;
44: } |
|
|
|
|
|
|
|
|
There are 1 cats alive
There are 2 cats alive
There are 3 cats alive
There are 4 cats alive
There are 5 cats alive
There are 4 cats alive
There are 3 cats alive
There are 2 cats alive
There are 1 cats alive
There are 0 cats alive |
|
|
|
|
|
|
|
|
Analysis: The static member variable HowManyCats is declared to have private access on line 15 of the Cat declaration. The public accessor function, GetHowMany(), is declared to be both public and static on line 12. |
|
|
|
|
|
|
|
|
Because GetHowMany() is public, it can be accessed by any function, and because it is static there is no need to have an object of type Cat on which to call it. Therefore, on line 43, the function TelepathicFunction() is able to access the public static accessor even though it has no access to a Cat object. Of course, you could have called GetHowMany() on the Cat objects available in main(), just as with any other accessor functions. |
|
|
|
|
|
|
|
|
Static member functions do not have a this pointer; therefore, they cannot be declared const. Also, because member data variables are accessed in member functions using the this pointer, static member functions cannot access any nonstatic member variables! |
|
|
|
|
|
|