程序設計與算法(三)期末考試之002:編程填空:統計動物數量

輸入

輸出

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

#include <iostream>
using namespace std;
//begin
class Animal
{
public:
	static int number;
	Animal(){number++;}
	virtual~Animal(){number--;}
};
int Animal::number=0;

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

class Cat:public Animal
{
public:
	static int number;
	Cat(){number++;}
	~Cat(){number--;}
};
int Cat::number=0;
//end
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();
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章