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

题目:

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

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值