【问题标题】:Virtual function does not overrides to latest inheriting object虚函数不会覆盖最新的继承对象
【发布时间】:2019-09-21 11:54:09
【问题描述】:

我有 3 个班级:ABCB 继承自 AC 继承自 B(所以 C 是孙子A)。
每个对象都有显示文本的函数 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;
    }

如果每个类之间都有 virtual talk()

,我希望 call(A &a) 采用最远的继承版本

【问题讨论】:

  • 您应该始终添加覆盖以清楚地表达覆盖基本虚函数的意图。这样,编译器将在运行时捕获错误,而不是在运行时以各种方式捕获神秘故障。

标签: c++ multiple-inheritance virtual-functions


【解决方案1】:

在您的示例中,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"; }
};

【讨论】:

  • 天哪,我现在因为错过了参数而变得如此愚蠢:/谢谢。
  • 很高兴我能帮上忙! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-27
  • 1970-01-01
  • 2012-02-05
  • 2011-01-10
  • 1970-01-01
相关资源
最近更新 更多