【发布时间】:2014-06-01 12:34:47
【问题描述】:
在网上搜索后,我没有找到这个问题的答案:
我有这个重载方法:
foo(Base* base);
foo(Derived* derived);
在这种情况下,“Derived”是“Base”的子类。
当我打电话时:
foo(new Derived());
我注意到总是调用第一个重载方法,而我想获得相反的结果(调用将“Derived*”对象作为参数的方法)。
如何解决这个问题?谢谢。
编辑:
好的,这是我的实际情况:
我有一个 UIWidget 和一个 UIScoreLabel 类。 UIScoreLabel 派生自 UIWidget。我还有一个 GameEvent 类(Base)和一个 P1ScoreGameEvent 类(Derived)。
UIWidget:
virtual void handleGameEvent(GameEvent* e) { printf("ui_widget"); }
UIScoreLabel:
virtual void handleGameEvent(P1ScoreGameEvent* e) { printf("ui_score_label"); }
这是电话:
UIWidget* scoreLabel = new UIScoreLabel();
scoreLabel.handleGameEvent(new P1ScoreGameEvent());
输出:
ui_widget
我不明白我做错了什么。
【问题讨论】:
-
minimal extension of your code 表明您的声明不正确。发布您的实际代码。
-
您的 UIScoreLabel.handleGameEvent 不会覆盖基类 UIWidget.handleGameEvent,因为它们采用不同的参数类型。您要么需要使 UIScoreLabel 将 UIWidget * 作为其参数(然后将覆盖基类)并使用 RTTI 检查其类型,要么在基类中重载两个参数列表并在继承类中派生。跨度>
-
@Dampsquid 谢谢你的回答。不过我不是很明白。您能否展示一个扩展我在下面给出的答案的代码示例?谢谢。
标签: c++ inheritance overloading