C++ 继承类静态变量虚函数练习

总时间限制: 

1000ms

 

内存限制: 

65536kB

// 在此处补充你的代码

描述

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

#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

 

显然,dog类,cat类继承animal类,类种有number成员变量,如果将number设为私有,那么print要申明为友元成员函数,这里为了简单,就将number设为公有。

要特别注意静态成员变量的初始化,以及~Animal的析构函数要用虚函数

#include <iostream>
using namespace std;

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

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

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

int Animal::number = 0;
int Dog::number = 0;
int 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();
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值