从超类调用子类的方法
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
除外。slow_bell
继承自bell
,并覆盖noise
方法。当调用slow_bell
的ring
方法时,它会返回到其父bell
,但当bell
的ring
方法调用noise
时,它被称为bell
的noise
方法,而我希望它调用slow_bell
的noise
方法。
实现这一目标的最佳方式是什么?
使它们成为virtual
和override
的方法:
贝尔:
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;
}
};
相关文章:
- 从父类方法返回子类对象
- c++, 在子类中,如何在没有对象的情况下访问父类的方法?
- 将子类方法声明为基类的友元
- 使用模板参数重载C++方法:如何使其适用于模板的子类?
- C++有没有办法强制重写一组方法,如果其中一个方法在子类中具有重写?
- C ++类型特征:确保子类实现方法
- 函数从唯一代码调用正确的子类方法
- Arduino在子类中使用父类方法
- C++强制在子类中实现方法,但具有不同的签名
- 我们可以在没有新实例化的情况下声明一个抽象方法来返回抽象超类中的子类对象吗
- 如何调用传递给 JNI 'jobject' 的 Java 对象的子类/子类的方法
- 将方法参数类型更改为子类中的派生类
- 如果指针的子类的方法对于子类是唯一的,如何访问这些方法?
- C++继承,如何在基类的方法中调用子类的方法?
- 在子类上调用模板化静态方法时获取类的类型名
- 检查子类是否执行了方法重写
- 将"this"从父类方法转换为子类方法是一种好的做法吗?
- 从C++中的父类实例访问子类方法
- 基类中的虚拟方法和子类中的非 Virtula 方法.仍然如何调用子类方法,即使它是非虚拟的
- C ,基础课程如何将子类作为成员包含并调用其方法