C++继承方法调用基class的方法而不是重载方法

C++ inherited methods call the base class's method instead of overloaded method

给定代码:

class A{
public:
    void callFirst()
    {
        callSecond();
    }
    void callSecond()
    {
        cout << "This an object of class A." << endl;
    }
};

class B : public A{
public:
    void callSecond()
    {
        cout << "This is an object of class B." << endl;
    }
};

int main()
{
    B b;
    b.callFirst();

    return 0;
}

我得到输出:

This an object of class A.

我该怎么做才能在调用派生 class 的继承方法时,它不会依次调用基础 class 的方法而不是重载的方法,除了重载第一个方法?

您必须标记 callSecond() 成员函数 virtual,否则您将以编译时绑定结束(相对于 运行-时间绑定)。

您应该将 callSecond 设为 class 虚拟。

#include<iostream>
using namespace std;
class A{
public:
    void callFirst()
    {
        callSecond();
    }
    virtual void callSecond()
    {
        cout << "This an object of class A." << endl;
    }
};

class B : public A{
public:
    void callSecond()
    {
        cout << "This is an object of class B." << endl;
    }
};

int main()
{
    B b;
    b.callFirst();

    return 0;
}