相关疑难解决方法(0)

使用非虚拟覆盖隐藏虚拟功能

#include <iostream>

using namespace std;

class A {
public:
    virtual void foo() {
        cout << "A" << endl;
    }
};

class B : public A {
public:
    void foo() {
        cout << "B" << endl;
    }
};

class C : public B {
public:
    void foo() {
        cout << "C" << endl;
    }
};

int main() {
    C c;
    B* b = &c;
    b->foo();

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出是C,但我预计B.

我没有B::foo()使用virtual修饰符声明,所以我希望函数调用由静态类型(无多态)决定.

为什么C::foo() …

c++ polymorphism inheritance overriding virtual-functions

10
推荐指数
1
解决办法
1661
查看次数