我有以下两节课。由于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++ - C++覆盖继承的方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33350175/

10-11 22:25
查看更多