0
看看这个例子,有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
方法。
达到此目的的最佳方法是什么?
*它们将覆盖bell' * ** **没了唐它们的'不同的方法他们只是影射(或继承)他们。阅读* polymorphism *的正确介绍,特别是'virtual','override'的使用,还有'= 0'和'final'的使用。 – Walter