我有一个基类和许多其他类(都是从基类派生的),它们都使用相同的参数实现相同的函数。我的问题是:强制调用“最高”重载函数而不是基函数
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