C++ 覆盖继承的方法

标签 c++ oop c++11 inheritance

我有以下两个类。由于 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/

相关文章:

c++ - 为什么这个编译成功?

c++ - 使用 noexcept 优化 std::bitset

PHP - 如何组合三个或更多相互依赖的类?

c# - 如何以比 C# 中的接口(interface)更宽松的方式定义模板

c++11 - std::map emplace gcc 4.8.2

c++ - 在命名空间中转发声明类

c++ - 如何在 C++11 中创建指向静态成员函数的指针映射?

php - 如何在数学类中创建减法方法?

c++11 - 返回统一的初始化引用是否有效?

c++ - 对于双映射