首页 > 解决方案 > 关于派生类如何工作的问题

问题描述

这是我期末考试的模拟测试。我必须能够解释这些代码是如何工作的。但老实说,我不太了解这段代码。你们能解释一下我这是如何工作的吗?如果我能完全理解它,我会很高兴为我的决赛做好准备。谢谢你。

   #include <iostream>
    using namespace std;
    class Wind {
        int category;
    public:
        Wind(int cat = 3) {
            category = cat;
            cout << "1." << cat << endl;
        }
        virtual void increase(int amount) {
            category += amount;
            cout << "A. " << category << endl;
        }
        void operator++() {
            ++category;
            cout << "B. " << category << endl;
        }
        virtual ~Wind() {
            cout << "C. " << category << endl;
        }
    };
    class Tornado : public Wind {
        double velocity;
    public:
        Tornado(int cat, double vel) : Wind(cat) {
            velocity = vel;
            cout << "2. " << vel << endl;
        }
        virtual void increase(int value) {
            velocity += value;
            cout << "X. " << velocity << endl;
        }
        void operator++() {
            Wind::operator++();
            velocity += 20;
            cout << "Y. " << endl;
        }
        ~Tornado() {
            cout << "Z. " << velocity << endl;
        }
    };
    int main() {
        Wind* wind_array[2];
        wind_array[0] = new Tornado(7, 66.5);
        wind_array[1] = new Wind(5);
        for (int i = 0; i < 2; i++) {
            wind_array[i]->increase(5);
            ++(*wind_array[i]);
        }
        for (int i = 0; i < 2; i++)
            delete wind_array[i];
        return 0;
    }

这是输出。

1.7
2. 66.5
1.5
X. 71.5
B. 8
A. 10
B. 11
Z. 71.5
C. 8
C. 11

标签: c++

解决方案


请阅读有关虚函数和派生类的内容,之后会有意义。

派生类

虚函数 cpp

1.7 -构造函数 wind (wind是tornado的基类所以先执行this构造函数)
2. 66.5 - 构造函数 tornado
1.5 -构造函数 wind
X. 71.5 -增加 tornado (虚拟函数所以不执行基类增加)
B. 8 - ++ (不是虚函数 - 所以龙卷风的 ++ 不会执行)
A. 10 -增加
B. 11 - ++
Z. 71.5 -破坏 龙卷风
C. 8 -破坏 (Wind 是基类)
C. 11 -析构函数 wind


推荐阅读