【发布时间】:2016-01-25 19:31:40
【问题描述】:
我有以下两个课程。由于Child 继承自Father,我认为Child::init() 会覆盖Father::init()。为什么,当我运行程序时,我得到的是“我是父亲”而不是“我是孩子”?如何执行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();
}
【问题讨论】:
-
您没有将
init函数设为虚拟(即virtual void init();)。 -
因为init不是
virtual,而start属于Father类所以它会调用那里定义的init。 -
孩子的
init()不会覆盖父亲的init()基本上Child::start()是Father::init()。 -
我很惊讶没有给出隐藏父方法的警告:(
-
阴影不是值得警告的事情,因为有时这正是程序员想要的:/
标签: c++ oop c++11 inheritance