用c++声明一个Cat类

声明一个Cat类,使其至少满足以下要求:

(1)拥有静态数据成员HowManyCats,记录Cat的个体数目。

(2)声明静态成员函数GetHowMany(),存取HowManyCats。

(3)能够以年龄作为构造函数参数,建立合理的构造函数

(4)能够合理实现程序中猫数量的增减。

(5)设计一个名为creating()的函数,该函数的主要功能为创建一个含有5个指向猫对象的指针数组,用于动态创建5个猫对象,猫的年龄分别为1,2,3,4,5。并显示数组创建前后情况下猫的数量。函数参数自拟。

(6)能够合理创建主程序,该主程序能够在调用函数creating()前后显示猫的数量,在体会静态数据成员和静态成员函数的用法。

【输入形式】该程序无输入,请仔细观察输出

【输出形式】输出结果如下图;

before the function,the number of the cat is:0

before the Cat array is created,the number of the cat is:0

after the Cat array is created,the number of the cat is:5

destructing of the cat!

destructing of the cat!

destructing of the cat!

destructing of the cat!

destructing of the cat!

after the function,the number of the cat is:0

代码如下:

#include <iostream>
using namespace std;
class Cat
{
private:
	int age;
	static int HowManyCats;
public:
	Cat(int a){age = a;HowManyCats++;}
	~Cat(){HowManyCats--;cout << "destructing of the cat!" << endl;}
	static int GetHowMany(){return HowManyCats;}
};

int Cat::HowManyCats = 0;
void creating(Cat* arr[],int n)
{
	int i = 0;
	for (; i < n; i++)
	{
		arr[i] = new Cat(i+1);
	}
}
//减去m个猫
void outcat(Cat* arr[],int n,int m)
{
	int i ;
	for (i = 0; i < m;i++)
	{
		delete arr[n -1-i];
		arr[n -1-i] = 0;
	}
}
int main()
{
	Cat* arr[5];
	cout << "before the function,the number of the cat is:" << Cat::GetHowMany() << endl;
	cout << "before the Cat array is created,the number of the cat is:" << Cat::GetHowMany() << endl;
	creating(arr,5);
	cout << "after the Cat array is created,the number of the cat is:"<< Cat::GetHowMany() << endl;
	outcat(arr,5,5);
	cout << "after the function,the number of the cat is:" << Cat::GetHowMany() << endl;
	return 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!

 

 

您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~

如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~

ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632