【问题标题】:calling a virtual function through a reference: derived class' override gets called通过引用调用虚函数:派生类的覆盖被调用
【发布时间】:2015-05-03 18:20:49
【问题描述】:

我有以下代码:

#include <iostream>
using namespace std;

class Parent {
public:
    virtual void f() { cout << "Parent" << endl; }
};

class Child : public Parent {
public:
    void f() { cout << "Child" << endl; }
};

void t1(Parent * p) { p->f(); }
void t2(Parent & p) { p.f(); }

int main() {
    Child a;

    t1(&a);
    t2(a);

    return 0;
}

我在 Visual Studio 2013 和 ideone.com 中都对此进行了测试,都得到了结果:

Child
Child

我可以理解 t1 调用 Child::f() 作为动态绑定的结果,但第二个让我感到困惑 - 我希望 Parent &amp; 能够“修复”类型,所以 t2 会调用 Parent::f() .我误解了规则吗?如何解释这种行为?

【问题讨论】:

  • 这就是虚拟多态性的期望?
  • I expected the Parent &amp; to "fix" the type 这个期望是基于什么?你能指出一段误导你的文件吗?
  • 我知道它适用于指针;所以引用也遵循相同的规则?
  • 是的。虽然看起来你并不完全理解这些规则;我们可以帮助您吗?
  • @martin_ljchan 晚上跳过派对,然后在第二天早上参加重要讲座,下次!

标签: c++ polymorphism dynamic-binding


【解决方案1】:

这就是多态性的作用。


我希望 Parent &amp; 能够“修复”该类型,因此 t2 会调用 Parent::f()

嗯,你猜错了。

我是不是对规则有误解?

是的。

如何解释这种行为?

通过拿起一本关于 C++ 的书并阅读关于多态性的章节。
您的 Parent&amp; 就像 Parent* 一样工作:通过允许虚拟调度

需要注意的重要一点是指针(和引用)不会调用多态性。所以无论你在哪里读到只有指针调用多态性是双重错误的。 多态性是由对象访问调用的。恰巧,由于the slicing problemit is impossible to invoke virtual dispatch except through a pointer or reference

【讨论】:

  • 开启invoking虚拟调度
  • 我一定是错过了关于指针和引用的虚拟调度工作的部分。感谢大家的帮助;额外的阅读也很感激:)
猜你喜欢
  • 1970-01-01
  • 2016-05-24
  • 1970-01-01
  • 2011-09-08
  • 1970-01-01
  • 2012-08-08
  • 2021-07-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多