2014-05-19 77 views
0

爲了好玩,我決定嘗試製作一個簡單的實體組件系統。我有一個包含所有組件的列表,並且我創建了一個名爲getPositionComponent的函數,它接受實體ID並返回與該實體相關的位置組件。我所做的所有組件都是從Components類派生的。dynamic_cast返回空指針

struct Component 
{ 
public: 
    std::string readableName; 
    Component::Component(); 
    Component(std::string name); 
    virtual ~Component(); 
}; 

位置分量

struct PositionComponent : 
     public Component 
    { 
    public: 
     PositionComponent(int x, int y); 
     ~PositionComponent(); 
     int x, y; 
    }; 

這是getPositionComponent怎麼看起來像

PositionComponent* ComponentManager::getPositionComponent(int entityID) { 
    int index = entitiesLookup_[entityID] + positionComponentsLookup_[entityID]; 

    Component *comp = &components_[index]; 
    PositionComponent* postionComponent = dynamic_cast<PositionComponent*>(comp); 

    if (postionComponent != nullptr) 
     return postionComponent; 
    return nullptr; 
} 

當我運行它,它總是當我使用的dynamic_cast返回nullptr。雖然debbuging我可以確認Component * comp = & components_ [index];返回正確的組件類型。

在附註上,我讀了一篇文章,他們使用SQL來存儲組件。在單個玩家遊戲中,如果將數據從本地遊戲循環中的組件拖動到本地,sql有多慢/多快?

+1

'components_'是什麼類型? –

+0

你可能希望在我們處於構造函數的時候接受'const std :: string&'而不是'Component'構造函數中的'std :: string'。 – zneak

回答

2

我要冒險在這裏猜測...

你是存儲在一個std::vector<Component>Compoent的List。當您將派生類Component存儲在std::vector中時,將丟失派生類的一部分。因此,dynamic_cast失敗。

您可以通過在「std :: vector」中存儲指向Components的指針列表來解決該問題。

通過確保基類是一個抽象基類,可以避免類似這樣的錯誤。

+0

啊,是的,我確實使用矢量,我試着將它改爲指針列表,謝謝。 – Ziamor

+1

「std :: vector」正在複製這些值,並且最終將「派生」對象切片爲「Component」基本類型。 – vsoftco