我有以下两个类。由于 Child
继承自 Father
,我认为 Child::init()
覆盖了 Father::init()
.为什么,当我运行程序时,我得到的是“我是父亲”而不是“我是 child ”?如何执行Child::init()
?
您可以在这里进行测试:https://ideone.com/6jFCRm
#include <iostream>
using namespace std;
class Father {
public:
void start () {
this->init();
};
void init () {
cout << "I'm the father" << endl;
};
};
class Child: public Father {
void init () {
cout << "I'm the child" << endl;
};
};
int main (int argc, char** argv) {
Child child;
child.start();
}
最佳答案
目前 Child::init
正在隐藏 Father::init
,而不是覆盖它。您的 init
成员函数需要是 virtual
才能获得动态调度:
virtual void init () {
cout << "I'm the father" << endl;
};
可选地,您可以将 Child::init
标记为 override
以明确您想要覆盖虚函数(需要 C++11):
void init () override {
cout << "I'm the child" << endl;
};
关于C++ 覆盖继承的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33350175/