2015-10-14 67 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