[英]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
方法。 当ring
法slow_bell
把它叫做回落到其父bell
但当ring
法bell
称noise
它被称为noise
的方法bell
,而不是我想它来调用noise
的方法slow_bell
。
实现此目标的最佳方法是什么?
使它们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;
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.