从超类调用子类的方法

时间:2015-11-14 19:28:12

标签: c++ inheritance

看看这个示例,有3个类继承自if。它们会覆盖bell的不同方法。

bell

输出:

#include <iostream>
using namespace std;

class bell {
public:
    void noise() {
        cout << "dung" << endl;
    }
    void ring() {
        noise();
        noise();
    }
};

class short_bell : public bell {
public:
    void ring() {
        noise();
    }
};

class annoying_bell : public bell {
public:
    void noise() {
        cout << "ding" << endl;
    }
    void ring() {
        noise();
        noise();
        noise();
        noise();
        noise();
    }
};

class slow_bell : public bell {
public:
    void noise() {
        cout << "dooong" << endl;
    }
};

int main()
{
    cout << "church bell" << endl;
    bell church_bell;
    church_bell.ring();

    cout << "bicycle bell" << endl;
    short_bell bicycle_bell;
    bicycle_bell.ring();

    cout << "doorbell" << endl;
    annoying_bell doorbell;
    doorbell.ring();

    cout << "school bell" << endl;
    slow_bell school_bell;
    school_bell.ring();

    return 0;
}

一切都按照我的预期运作,但是church bell dung dung bicycle bell dung doorbell ding ding ding ding ding school bell dung dung school_bell继承自slow_bell并覆盖bell方法。当调用noise ring方法时,它会回退到其父slow_bell,但当bell ring方法调用bell时,它会回归noise称为noise的{​​{1}}方法,而我希望它调用bell的{​​{1}}方法。

实现这一目标的最佳方法是什么?

1 个答案:

答案 0 :(得分:2)

让他们virtualoverride方法:

贝尔:

class bell {
public:
    virtual void noise() {
        cout << "dung" << endl;
    }
    void ring() {
        noise();
        noise();
    }
};

slow_bell:

class slow_bell : public bell {
public:
    void noise() override {
        cout << "dooong" << endl;
    }
};