欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2024-03-17 18:07:04
...

题目:

http://cxsjsxmooc.openjudge.cn/2021t3springall2/026/

分析:

这题考的是静态成员和虚函数以及派生类成员覆盖基类成员的特性。本题的要点是:

  1. 如果要在类外访问静态成员,则必须把这个静态成员放在public中。
  2. 当派生类成员中有覆盖基类成员(同名)时,在派生类中访问成员时要加上类名前缀。
  3. 虚拟化析构函数,实现使用基类指针下析构派生类。
  4. 静态变量一定要记得初始化!!!在全局中作初始化即可。

参考代码:

#include <iostream>
using namespace std;
// 在此处补充你的代码
class Animal{
public:
    static int number;
    Animal() {}
    virtual ~Animal(){
        number--;
    }
};

class Dog:public Animal{
public:
    static int number;
    Dog(){
        Animal::number++; //wo need to point out that which "number" is.
        Dog::number++;
    }
     virtual ~Dog(){
        number--;
    }
};

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

//never forget to initiate the variable !!!
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; //class Dog
    Cat c1; //class Cat
    print();
    Dog* d3 = new Dog();
    Animal* c2 = new Cat; //class Animal, class Animal is the basic of class Dog and Cat
    Cat* c3 = new Cat; //why is it different from new Dog() ?
    print();
    delete c3;
    delete c2;
    delete d3;
    print();
}