定义一个 Cat 类,拥有静态数据成员 HowManyCats,记录 Cat 的个体数目;静态成员函 数 GetHowMany(),存取 HowManyCats。设计程序测试这个类,体会静态数据成员和静态 成员函数的用法。
#include <iostream> using namespace std; class Cat { private: static int HowManyCat; public: Cat(){HowManyCat++;} static int GetHowMany(){return HowManyCat;} ~Cat(){HowManyCat--;} }; int Cat::HowManyCat = 0; int main() { const int CatsNum = 10; Cat *CatFamily[CatsNum];//对象指针数组(每一个数组成员都是一个指针对象) int i = 0; for(i = 0; i < CatsNum; i++) { CatFamily[i] = new Cat; cout<<"There remain "<<Cat::GetHowMany()<<" Cats!"<<endl; } for(i = 0; i < CatsNum; i++) { delete CatFamily[i]; cout<<"There remain "<<Cat::GetHowMany()<<" Cats!"<<endl; } return 0; } 程序运行结果: There remain 1 Cats! There remain 2 Cats! There remain 3 Cats! There remain 4 Cats! There remain 5 Cats! There remain 6 Cats! There remain 7 Cats! There remain 8 Cats! There remain 9 Cats! There remain 10 Cats! There remain 9 Cats! There remain 8 Cats! There remain 7 Cats! There remain 6 Cats! There remain 5 Cats! There remain 4 Cats! There remain 3 Cats! There remain 2 Cats! There remain 1 Cats! There remain 0 Cats!
解:
源程序:
程序运行输出:
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!