一、问题描述
【问题描述】定义一个Cat类,拥有数据成员itsAge记载Cat的年龄;静态数据成员HowManyCats,记录Cat的个体数目;静态成员函数GetHowMany(),存取HowManyCats。设计程序测试这个类,体会静态数据成员和静态成员函数的用法。
【输入形式】无
【输出形式】
【样例输入】无
【样例输出】
Cat1age=1
There are 1 cats alive!
Cat2age=2
There are 2 cats alive!
Cat3age=3
There are 3 cats alive!
Cat4age=4
There are 4 cats alive!
Cat5age=5
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!
二、代码实现
#include<iostream>
using namespace std;
class Cat
{
private:
int itsAge;
static int HowManyCats;//静态数据成员,类内定义,类外声明
public:
//静态成员函数,可在类体内定义,也可在类体内声明类体外定义
static int GetHowMany()
{
return HowManyCats;
}
Cat(int itsAge);
~Cat();
};
int Cat::HowManyCats=0;
Cat::Cat(int itsAge)
{
this->itsAge=itsAge;
++HowManyCats;
cout<<"There are "<<HowManyCats<<" cats alive!"<<endl;
}
Cat::~Cat()
{
--HowManyCats;
cout<<"There are "<<HowManyCats<<" cats alive!"<<endl;
}
int main()
{
cout<<"Cat1age=1"<<endl;
Cat c1(1);
cout<<"Cat2age=2"<<endl;
Cat c2(2);
cout<<"Cat3age=3"<<endl;
Cat c3(3);
cout<<"Cat4age=4"<<endl;
Cat c4(4);
cout<<"Cat5age=5"<<endl;
Cat c5(5);
return 0;
}