C++ 强制要求「;最高的;重载函数而不是基函数
我有一个基类和许多其他类(都是从基类派生的),它们都用相同的参数实现相同的函数。我的问题如下:C++ 强制要求「;最高的;重载函数而不是基函数,c++,function,inheritance,overloading,C++,Function,Inheritance,Overloading,我有一个基类和许多其他类(都是从基类派生的),它们都用相同的参数实现相同的函数。我的问题如下: 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()
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
apaPlayer
调用distance(e,p)
,则调用相应的函数重载,而不是实体的实现
如果可能的话,我将如何实现这一点?我在这里搜索了很多,找到的最接近的问题是在完全不同的上下文中使用模板,所以它并没有真正帮助我:
提前感谢。正如@Amit在评论中所述,您正在寻找虚拟函数。您可以按如下方式更新实体
类:
class Entity
{
public:
// Add a virtual destructor to allow deletion through base pointer to work correctly
// (e.g., E* e = new Player(); delete e;)
virtual ~Entity();
virtual int getx() const = 0; // 'const' isn't related to your question but
virtual int gety() const = 0; // good to have, '= 0' is optional but helpful if
// the base class isn't providing an implementation
};
假设C++11,在派生类中使用override
也很好
class Enemy : public Entity
{
public:
// 'const' only necessary if specified in the base class
// 'virtual' is more documentation it would still be virtual if omitted
// 'override' enforces that the signature matches a virtual function
virtual int getx() const override;
virtual int gety() const override;
};
实际上,您要做的是OOP中的一个基本概念:虚拟函数
这个想法和你描述的一模一样:
虚函数是通过基类指针访问时被子类实现替换的函数
语法非常简单,只需将关键字virtual
添加到基类函数声明中即可。使用override
关键字标记覆盖函数(子类的函数)是一种良好的做法(尽管不是一种要求)
这是一个例子
您可以将代码更改为:
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
}
向问好。他可能仍然想要一个可构造的基类。这段代码假定有一个抽象的基。@JorenHeit它不假定任何东西。它明确指出,=0
是可用的和可选的,因为OP没有意识到虚拟函数,所以可以很安全地假设他们也没有意识到=0
(它是在代码中提供的,这样OP可以准确地看到它的使用位置,而不是仅仅评论它可以使用)。对不起,遗漏了那个注释。这两个函数getx()和gety()实际上是在实体中实现的。有一些派生自实体的类并没有实现它们,所以应该调用实体的类。您的实现是否仍然可以这样做?编辑:没关系,我实际上读过文档,当然它是有效的。@Matrefeytontias如果基类提供了一个实现,并且您不想在派生类中执行任何操作,那么就不要在基类中使用=0
。此外,即使您使用=0
,您仍然可以在基类中提供一个实现,但是派生类将被迫声明并实现虚拟函数,即使它们所做的只是调用基类实现(我猜这不是您想要的)。