【发布时间】: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 & 能够“修复”类型,所以 t2 会调用 Parent::f() .我误解了规则吗?如何解释这种行为?
【问题讨论】:
-
这就是虚拟多态性的期望?
-
I expected the Parent & to "fix" the type这个期望是基于什么?你能指出一段误导你的文件吗? -
我知道它适用于指针;所以引用也遵循相同的规则?
-
是的。虽然看起来你并不完全理解这些规则;我们可以帮助您吗?
-
@martin_ljchan 晚上跳过派对,然后在第二天早上参加重要讲座,下次!
标签: c++ polymorphism dynamic-binding