为什么继承失败(使用超类的方法)

Why does this inheritance fail (method of super class is used) C++

本文关键字:超类 方法 继承 失败 为什么      更新时间:2023-10-16

我有以下类

#include <iostream>
using namespace std;
class A {
public:
    int get_number() {return 1;}
    void tell_me_the_number() {
        cout << "the number is " << get_number() <<"n";
    }
};
class B: public A {
public:
    int get_number() {return 2;}
};

int main() {
    A a;
    B b;
    a.tell_me_the_number();
    b.tell_me_the_number();
}

我希望这个输出给我:

the number is 1
the number is 2

但实际上我得到的是1号线的两倍。

类B的get_number()方法当它是类B时不应该被调用吗?如果这是应该的,我如何才能获得我想要的行为?

您需要将get_number标记为virtual才能正常工作。

在c++中,一分钱一分货。由于多态性增加了开销(内存和运行时),因此指向虚拟方法表的指针&动态调度),您必须明确希望在运行时解析哪些函数调用。由于get_number不是virtual,来自tell_me_the_number的调用将在编译时解析,并将调用基类版本。