首页 > 解决方案 > 虚函数不会覆盖最新的继承对象

问题描述

我有 3 个班级:ABCB继承自AC继承自B(因此CA的孙子)。
每个对象都有显示文本的函数talk(),在AB中它是虚拟的。
让外部函数call( A &a),它通过引用获取对象A ,并调用函数talk()
将对象C发送到函数,它使用B中的talk()而不是C,即使在B talk()是虚拟的。
为什么会这样?如何使它从C调用版本?

    #include <iostream>
    using namespace std;

    class A {
    public:
        virtual void talk() = 0;
        virtual void say() = 0;
    };

    class B : public A  {
    public:
        virtual void talk() // Why C does not overrides this?
        {   cout << "hello\n";  }   
    };

    class C : public B  {
    public:
        void talk (int a)   // It should override B.talk();
        { cout << "bye\n";}
        virtual void say()  { cout << "my name\n"; }
    };

    void call(A &a) {
        a.talk();   // Why does it call virtual talk() from B rather than from C?
        a.say();    // This was found so it knows about object C
    }

    int main()  {
        C c;
        call(c);
        system("PAUSE");
        return 0;
    }

如果每个类之间都有虚拟talk(),我希望call(A &a)采用最远的继承版本

标签: c++multiple-inheritancevirtual-functions

解决方案


在您的示例中,C.talk(int)不会覆盖B.talk(),因为C.talk将 int 作为参数,因此它是一个完全不同的函数。

您可以override在函数声明之后添加以使编译器检查它是否实际上覆盖了任何内容:

class C : public B  {
   public:
    // Here, the compiler complains because there's no talk(int) method
    // That it can override
    void talk (int a) override;
    { cout << "bye\n";}
    virtual void say()  { cout << "my name\n"; }
};

推荐阅读