一个C++问题,急求解答!~~~

来源:百度知道 编辑:UC知道 时间:2024/07/01 06:14:11
定义一个Cat类,拥有静态数据成员HowManyCats,记录Cat的个体数目;静态成员函数GetHowMany(),存取HowManyCats.设计程序测试这个类,体会静态数据成员和静态成员函数的用法.

#include <iostream>
using namespace std;

class Cat
{
private:
static int HowManyCats;
public:
Cat()
{
HowManyCats++;
}
static int GetHowMany();
};
int Cat::HowManyCats = 0;//静态数据成员类内声明,类外初始化
int Cat::GetHowMany()
{
return HowManyCats;
}

int main()
{
cout<<"the number of the cat is:"<<Cat::GetHowMany()<<endl;//输出为生成对象前的个数 0 此时没有生成对象所以用 Cat::
Cat c1;
Cat c2;
cout<<"the number of the cat is:"<<Cat::GetHowMany()<<endl;//输出产生两个对象后的个数 2
//或者使用cout<<"the number of the cat is:"<<c2.GetHowMany()<<endl;
}