首页 > 试题广场 >

定义一个 Cat 类,拥有静态数据成员 HowManyCat

[问答题]

定义一个 Cat 类,拥有静态数据成员 HowManyCats,记录 Cat 的个体数目;静态成员函 数 GetHowMany(),存取 HowManyCats。设计程序测试这个类,体会静态数据成员和静态 成员函数的用法。

推荐

解:

源程序:

#include <iostream.h>
class Cat
{
public:
Cat(int age):itsAge(age){HowManyCats++; }
virtual ~Cat() { HowManyCats--; }
virtual int GetAge() { return itsAge; }
virtual void SetAge(int age) { itsAge = age; }
static int GetHowMany() { return HowManyCats; }
private:
int itsAge;
static int HowManyCats;
};
int Cat::HowManyCats = 0;
void TelepathicFunction();
int main()
{
const int MaxCats = 5;
Cat *CatHouse[MaxCats]; int i;
for (i = 0; i<MaxCats; i++)
{
CatHouse[i] = new Cat(i);
TelepathicFunction();
}
for ( i = 0; i<MaxCats; i++)
{
delete CatHouse[i];
TelepathicFunction();
}
return 0;
}
void TelepathicFunction()
{
cout << "There are " << Cat::GetHowMany() << " cats alive!\n";
}

程序运行输出:

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!



发表于 2018-04-18 20:51:16 回复(0)
#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!
发表于 2019-11-09 16:10:10 回复(0)