1. 程式人生 > >C++ 繼承類靜態變數虛擬函式練習

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();
}