pis*_*hio 8 c++ oop inheritance c++11
我有以下两个班级.自从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();
}
Run Code Online (Sandbox Code Playgroud)
Tar*_*ama 12
目前Child::init正在隐藏 Father::init,而不是覆盖它.您的init成员函数需要是virtual为了获得动态调度:
virtual void init () {
cout << "I'm the father" << endl;
};
Run Code Online (Sandbox Code Playgroud)
(可选)您可以标记Child::init为override要显式覆盖虚拟函数(需要C++ 11):
void init () override {
cout << "I'm the child" << endl;
};
Run Code Online (Sandbox Code Playgroud)
您应该使用函数说明符定义函数virtual
例如
#include <iostream>
using namespace std;
class Father {
public:
virtual ~Father() {}
void start () {
this->init();
};
virtual void init () const {
cout << "I'm the father" << endl;
};
};
class Child: public Father {
void init () const override {
cout << "I'm the child" << endl;
};
};
int main()
{
Child child;
child.start();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
否则,函数在其自己的类的范围内start搜索名称。init并且因为函数init不是虚拟的,也就是说它不会在派生类中被重写,所以基类函数 init 被调用。