我有一個基類和許多其他類(都是從基類派生的),它們都使用相同的參數實現相同的函數。我的問題是:強制調用「最高」重載函數而不是基函數
class Entity
{
public:
int getx();
int gety();
};
class Enemy : public Entity
{
public:
int getx();
int gety();
};
class Player : public Entity
{
public:
int getx();
int gety();
};
// all of the implementations actually differ
int distance(Entity *e1, Entity *e2)
{
return e2->getx() + e2->gety() - e1->getx() - e2->gety();
// here, it is always Entity::getx and Entity::gety that are called
}
我想的是,如果我打電話,說,distance(e, p)
與e
的Enemy
和p
一個Player
,相應的函數重載被稱爲,而不是實體的實現。
如果實際上可行,我該如何實現這一目標?我在這裏搜索了很多,我發現最接近的問題是在相當不同的背景下使用模板,所以它並沒有真正幫助我:Template function overload for base class
感謝提前。
問好[虛函數(http://en.cppreference.com/w/cpp/language/virtual)。 – Amit