C++方法重载:基本和派生参数

Mic*_*ele 5 c++ inheritance overloading

在网上搜索后,我找不到这个问题的答案:

我有这个重载的方法:

foo(Base* base);
foo(Derived* derived);
Run Code Online (Sandbox Code Playgroud)

在这种情况下,"Derived"是"Base"的子类.
我打电话的时候:

foo(new Derived());
Run Code Online (Sandbox Code Playgroud)

我注意到总是调用第一个重载方法,而我想实现相反的结果(调用以"Derived*"对象作为参数的方法).

怎么解决这个?谢谢.

编辑:

好的,这是我的实际情况:

我有一个UIWidget和一个UIScoreLabel类.UIScoreLabel派生自UIWidget.我还有一个GameEvent类(B​​ase)和一个P1ScoreGameEvent类(Derived).

UIWidget:

virtual void handleGameEvent(GameEvent* e) { printf("ui_widget"); }
Run Code Online (Sandbox Code Playgroud)

UIScoreLabel:

virtual void handleGameEvent(P1ScoreGameEvent* e) { printf("ui_score_label"); }
Run Code Online (Sandbox Code Playgroud)

这是电话:

UIWidget* scoreLabel = new UIScoreLabel();
scoreLabel.handleGameEvent(new P1ScoreGameEvent());
Run Code Online (Sandbox Code Playgroud)

输出:

ui_widget
Run Code Online (Sandbox Code Playgroud)

我不明白我做错了什么.

mer*_*011 5

实际上,我从你那里得到了相反的结果,采用更派生类型的方法优先。在下面的演示代码中,默认情况下似乎会调用采用“Derived”的方法。但是,您始终可以通过指针强制转换来强制执行它。

#include <stdio.h>
#include <iostream>

class Foo {
    public:
    virtual void perform() {
       printf("Foo is on stage!\n"); 
    }
   virtual void dance() {
       printf("Foo is on dancing!\n"); 
   }
};

class Bar : public Foo {
   public:
   void perform() {
       printf("Bar is on stage!\n"); 
   }
   void dance() {
       printf("Bar is on dancing!\n"); 
   }
};

int m1 (Foo* foo) {
    foo->perform();
}
int m1 (Bar* foo) {
    foo->dance();
}
int main(){
    m1(new Bar); // Calls m1(Foo*)
    m1((Foo*) new Bar); // Calls m1(Bar*)
}
Run Code Online (Sandbox Code Playgroud)

输出:

Bar is on dancing!
Bar is on stage!
Run Code Online (Sandbox Code Playgroud)

请注意,它bar的方法两次被调用(这是正确的多态行为!),但它是由每个重载调用的不同方法,以消除歧义。bar