022:编程填空:统计动物数量

022:编程填空:统计动物数量

题面

描述

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

#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

思路

显然需要定义一个基类然后 派生出Dog类,和Cat类,又因为要统计所有的数量,显然是静态变量。

观察代码发现new 出对象赋给相应类的指针,其中还执行了Animal* c2 = new Cat;,要让其正常析构保证动物数量不改变,只能定义虚析构函数。

如果基类的析构函数是虚函数,那么派生类的也都是虚函数。

在用基类指针delete时候如果想要保证动物数量正确,那么只能定义基类的析构函数为虚析构函数,这样在delete时候会先调用派生类的析构函数,然后调用到基类的析构函数。

#include <iostream>
using namespace std;
class Animal {

public:
	static int number;
	Animal() {
		++number;
	}
	virtual ~Animal() {
		--number;
	}
};

class Dog:public Animal {
public:
	static int number;
	Dog() {
		++number;
	}
	~Dog() {
		--number;
	}
};


class Cat:public Animal {
public:
	static int number;
	Cat() {
		++number;
	}
	~Cat() {
		--number;
	}


};
int Animal::number = 0, Dog::number = 0, Cat::number = 0;

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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值