从超类调用子类的方法

Call method of subclass from superclass

本文关键字:方法 子类 调用 超类      更新时间:2023-10-16

看看这个例子,有3个类继承自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方法。当调用slow_bellring方法时,它会返回到其父bell,但当bellring方法调用noise时,它被称为bellnoise方法,而我希望它调用slow_bellnoise方法。

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

使它们成为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;
    }
};