c++编程练习 019:统计动物数量

半城伤御伤魂 提交于 2020-02-21 11:20:29

北大程序设计与算法(三)测验题汇总(2020春季)


描述

代码填空,使得程序能够自动统计当前各种动物的数量

#include <iostream>
using namespace std;
// 在此处补充你的代码
void print() {
	cout << Animal::number << " animals in the zoo, " << Dog::number << " of them are dogs, " << Cat::number << " of them are cats" << endl;
}

int main() {
	print();
	Dog d1, d2;
	Cat c1;
	print();
	Dog* d3 = new Dog();
	Animal* c2 = new Cat;
	Cat* c3 = new Cat;
	print();
	delete c3;
	delete c2;
	delete d3;
	print();
}

输入

输出
0 animals in the zoo, 0 of them are dogs, 0 of them are cats
3 animals in the zoo, 2 of them are dogs, 1 of them are cats
6 animals in the zoo, 3 of them are dogs, 3 of them are cats
3 animals in the zoo, 2 of them are dogs, 1 of them are cats

样例输入
None

样例输出
0 animals in the zoo, 0 of them are dogs, 0 of them are cats
3 animals in the zoo, 2 of them are dogs, 1 of them are cats
6 animals in the zoo, 3 of them are dogs, 3 of them are cats
3 animals in the zoo, 2 of them are dogs, 1 of them are cats


分析

此处利用构造函数与析构函数引起数据变化;
发现每定义一个类的对象,就会产生数量加1,那么知道在构造函数内部有一个累加变量,然后每次销毁一个对象的时候,数量会减1,那么可知在析构函数内部有减1的设计。

此处需要注意的是Animal* c2 = new Cat;delete c2;由于此处是基类指针指向的派生类,那么在调用析构函数的时候,基类的析构函数必须是虚函数,因为这样才能保证先调用派生类的析构函数,然后调用基类的析构函数,两者不缺。


解决方案

#include <iostream>
using namespace std;
class Animal{
public:
	static int total_Animal;
	Animal(){ total_Animal ++;}
	virtual ~Animal(){ total_Animal--;}		
}; 
class Dog:public Animal{
public:
	static int Dog_num;
	Dog(){Dog_num++;}
	~Dog(){Dog_num--;}		
};
class Cat:public Animal{
public:
	static int Cat_num;
	Cat(){Cat_num++;}		
	~Cat(){Cat_num--;}
};
int Animal::total_Animal = 0,Dog::Dog_num = 0,Cat::Cat_num = 0;
void print() {
	cout << Animal::total_Animal << " animals in the zoo, " << Dog::Dog_num << " of them are dogs, " << Cat::Cat_num << " of them are cats" << endl;
}

int main() {
	print();
	Dog d1, d2;
	Cat c1;
	print();
	Dog* d3 = new Dog();
	Animal* c2 = new Cat;
	Cat* c3 = new Cat;
	print();
	delete c3;
	delete c2;
	delete d3;
	print();
}

执行效果
在这里插入图片描述

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!