C++ : What is happening when a non-overridden calls a overridden method?

标签 c++ overriding member-hiding

被调用的覆盖方法的版本取决于 如果您关心“通过”基类或“通过”派生类调用函数。但是,我发现如果我调用一个非重写方法,并且重写方法调用一些重写的函数,那么基类版本仍然被调用,即使我通过指针访问实例到派生类。有人可以解释为什么会这样吗?

代码:

class Base {
public:
    void display() {
        foo();
    }
    void foo() {
        cout << "Base.foo()" << endl;
    }
};

class Derived : public Base {
public:
    void foo() {
        cout << "Derived.foo()" << endl;
    }
};

int main() {
    Derived* derived = new Derived();
    derived->display();
    while (true) {}
}

最佳答案

the base class version is still called, even though I am accessing the instance through pointer to the derived class. Could someone explain why this happens?

虽然您通过指向派生类的指针调用方法,但您的方法不是虚拟的,因此使用静态分派(dispatch),所以 Base::display() 调用 Base::foo() 直接,即使它在子类中被覆盖。要实现您想要的行为,您必须使用动态调度,即将您的方法标记为 virtual

class Base {
public:
    void display() {
        foo();
        bar();
    }
    void foo() {
        cout << "Base.foo()" << endl;
    }
    virtual void bar() {
        cout << "Base.bar()" << endl;
    }
};

class Derived : public Base {
public:
    void foo() {
        cout << "Derived.foo()" << endl;
    }
    virtual void bar() {
        cout << "Derived.bar()" << endl;
    }
};

int main() {
    Derived* derived = new Derived();
    derived->display();
}

输出:

Base.foo()
Derived.bar()

关于C++ : What is happening when a non-overridden calls a overridden method?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33334313/

相关文章:

java - 从隐藏字段的类的子类访问隐藏字段

c++ - Boost::variant 无法为 std::ostream 解析运算符<<

c# - 多态和类型转换

Java 字段隐藏

c++ - 我应该在哪里重新实现 QAbstractItemModel::supportedDragActions()?

webpack - Chrome 开发者工具 : local overrides for JS files from Webpack Source Map

c++ - c++中的重写函数

c++ - 巨大的 vector "hangs"程序? (50000 x 50000 个细胞)

c++ - cmake:如何检查库的运行时?

c++ - 如何从 HBITMAP 获取 RGBQUAD?