2015-10-14 72 views
1

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

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)eEnemyp一个Player,相应的函数重载被称为,而不是实体的实现。

如果实际上可行,我该如何实现这一目标?我在这里搜索了很多,我发现最接近的问题是在相当不同的背景下使用模板,所以它并没有真正帮助我:Template function overload for base class

感谢提前。

+3

问好[虚函数(http://en.cppreference.com/w/cpp/language/virtual)。 – Amit

回答

0

你想要做的实际上是在OOP的基本概念之一:虚函数

的想法是完全按照你描述的那样:

虚函数是可以被执行的子类时,通过一个基类指针访问被取代的功能。

的语法是相当直接的,简单的关键字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 
} 
0

作为@Amit在您要查找虚拟功能的注释中声明状态。您可以按以下步骤更新您的Entity类:

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; 
}; 
+0

他可能仍然需要一个可构造的基类。此代码假定抽象基础。 – JorenHeit

+0

@JorenHeit它不承担任何事情。它清楚地表明'= 0'可用并且_optional_,因为OP没有意识到虚函数,所以假设它们不知道'= 0'是非常安全的(它是在代码中提供的,以便OP可以确切地看它在哪里使用,而不是评论它可以被使用)。 –

+0

对不起,错过了评论。 – JorenHeit