看看这个示例,有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}}方法。
实现这一目标的最佳方法是什么?
答案 0 :(得分:2)
让他们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;
}
};