2012-11-22 176 views
3

我是C++的新手,我很難弄清楚我的虛擬函數有什麼問題。所以,這裏是我有:

GEntity.h從基類C++調用虛擬方法

class GEntity 
{ 
public: 
    //... 
    virtual void tick(void); 
    virtual void render(void); 
    //... 
}; 

GEntity.cpp

//... 
void GEntity::tick(void){} 
void GEntity::render(void){} 
//... 

GLiving.h

class GLiving : public GEntity 
{ 
public: 
    //... 
    virtual void tick(void); 
    virtual void render(void); 
    //... 
}; 

GLiving.cpp

//... 
void GEntity::tick(void){} 
void GEntity::render(void){} 
//... 

然後,我有從GLiving(玩家,敵人),它們實現了自己的這兩種方法的版本獲得其他類: Player.h

class Player : public GLiving 
{ 
public: 
    //... 
    void tick(void); 
    void render(void); 
    //... 
}; 

Player.cpp

//... 
void GEntity::tick(void) 
{ 
    //Here there's some actual code that updates the player 
} 
void GEntity::render(void) 
{ 
    //Here there's some actual code that renders the player 
} 
//... 

現在,如果我聲明一個Player類的對象,並調用render/tick方法,一切都很順利,但是我處於一種情況,我將我的播放器添加到GEntity的ArrayList(一個我創建的結構體),然後,當我將它返回時,我得到它作爲一個GEntity,我需要調用渲染/滴答方法,而不知道它的派生類... 我已經嘗試使用上面的代碼,但我得到一個訪問衝突行中,我打電話或者渲染或刻度方法,對提取的GEntity ...
...是我想甚至可以實現的目標?
(抱歉,如果我的英語不太好,但我是意大利)

+3

這個問題可能存在於'arraylist'中。它是否包含指向「GEntity」或「GEntity」實際實例的指針? – Yakk

+0

數組/結構聲明怎麼樣?這是關鍵。 – Ajay

+0

它包含實際實例 – Sylar

回答

3

如果你有GEntity一個數組,那麼,每次「加」派生型,這相當於情況:

GEntity g; 
Player p; 
g = p; // object slicing, you assigned a Player to a GEntity object. 
g.render(); // GEntity::render() gets called 

在另一方面,可以使用一個指針指向一個基類來訪問派生方法:

GEntity* g; 
Player p; 
g = &p; 
g->render(); // calls Player::render() 

因此,一個方法來處理多態性的容器被以具有陣列/容器(優選智能)指向基本cl的指針屁股。這個例子使用原始指針爲簡單起見,但你應該在實際代碼中使用smart pointers

std::vector<CEntity*> entities; 
entities.push_back(new Player); 
entities.push_back(new GLiving); 

// some c++11 
for (auto e : entities) { 
    e->render(); 
} 
+0

你不應該寫'for(_auto_e:entities) '? – Mikhail

+0

@Mikhail確實,謝謝! – juanchopanza

+0

好,謝謝!有效! ...我仍然習慣Java – Sylar