繁体   English   中英

父类的子类的调用方法

[英]Call method of subclass from superclass

看一下这个示例,有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一切都按我预期的school_bell slow_bell继承自bell并覆盖noise方法。 ringslow_bell把它叫做回落到其父bell但当ringbellnoise它被称为noise的方法bell ,而不是我想它来调用noise的方法slow_bell

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM