我有以下代码:
#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()
作为动态绑定(bind)的结果,但是第二个让我感到困惑-我期望Parent &
可以“修复”该类型,因此t2
将调用Parent::f()
。我误会了规则吗?如何解释这种行为? 最佳答案
这就是多态性。
好吧,你期望错了。
是。
通过挑选一本有关C++的书并阅读有关多态性的章节。
您的Parent&
就像Parent*
一样:通过允许虚拟调度。
需要注意的重要一点是指针(和引用)不会调用多态性。因此,无论您在何处看到只有指针调用多态性,都是双重错误。 多态由对象访问调用。 正是由于the slicing problem和it is impossible to invoke virtual dispatch except through a pointer or reference而发生的。
关于c++ - 通过引用调用虚拟函数:派生类的重写被调用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30017634/