我有一个基类和许多其他类(全部派生自基类),它们都使用相同的参数实现相同的功能。我的问题如下:
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
}
我想要的是,如果我用 e
调用 distance(e, p)
一个 Enemy
和 p
Player
,调用各自的函数重载,而不是实体的实现。
如果真的可行,我将如何实现?我在这里搜索了很多,我发现最接近的问题是在完全不同的上下文中使用模板,所以它并没有真正帮助我:Template function overload for base class
提前致谢。
最佳答案
您尝试做的实际上是 OOP 中的基本概念之一:虚拟函数。
这个想法和你描述的完全一样:
A virtual function is a function that's being replaced by subclasses implementation when accessed via a base class pointer.
语法非常简单,只需将关键字 virtual
添加到您的基类函数声明即可。使用 override
关键字标记覆盖函数(子类的函数)是一种很好的做法(尽管不是必需的)。
这是一个 reference of virtual functions .
您可以将代码更改为:
class Entity
{
public:
virtual int getx();
virtual int gety();
};
class Enemy : public Entity
{
public:
int getx() override;
int gety() override;
};
class Player : public Entity
{
public:
int getx() override;
int gety() override;
};
// all of the implementations actually differ
int distance(Entity *e1, Entity *e2)
{
return e2->getx() + e2->gety() - e1->getx() - e2->gety();
// Now, the proper getx & gety are being called
}
关于c++ - 强制调用 "highest"重载函数而不是基函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33135034/