北大程序設計與算法(三)測驗題彙總(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();
}
執行效果