2014-03-06 17 views
0

我有接口,看起來像這樣:C++不能通過參照指針當函數ARG類型是類接口

class IGameObject 
{ 
public: 
    virtual ~IGameObject(){} 
    virtual void Notify(Massage message) = 0; 
    virtual void SendMessages() = 0; 
}; 

class WinFrameObj :public Sprite , public BaseGameObject<WinFrameObj> 
{ 
    public: 

     WinFrameObj(); 
     virtual ~WinFrameObj(){}; 
     static WinFrameObj* createInternal();   
     void Notify(Massage message); 

}; 
template<typename T> 
class BaseGameObject : public IGameObject 
{ 
    public: 
     BaseGameObject(){}; 

     virtual ~BaseGameObject(){}; 

     static T* createObj() 
     { 
      return T::createInternal(); 
     } 

}; 

// Simple catch class 
typedef std::map<GameObjectType, IGameObject*> ComponentsMap; 
class ComponentMadiator{ 

.... 
.... 
void ComponentMadiator::Register(const GameObjectType gameObjectType,IGameObject*& gameObj) 
{ 
    componentsMap[GameObjectType] = gameObj; // THIS is std map 
} 
... 
... 

} 

現在我在代碼 做在主類

WinFrameObj* m_pMainWindowFrameObjCenter ; // defined in the header as memeber 
pMainWindowFrameObjCenter = WinFrameObj::createObj(); 
ComponentMadiator::Instance().Register(MAIN_WIN_FRAME,pMainWindowFrameObjCenter); 

即時得到這個錯誤:

error C2664: 'ComponentMadiator::Register' : cannot convert parameter 2 from 'WinFrameObj *' to 'IGameObject *&' 

我需要的ComponentMadiator ::註冊方法是根埃裏克有配發是從類型IGameObject對象,它必須通過參考指針

UPDATE
我這樣做是爲了保持我存儲在地圖中的數據是隨時間持久的原因。 如果我通過指針只能傳遞,然後我嘗試調用該對象是這樣的:

IGameObject* ComponentMadiator::getComponentByObjType(GameObjectType gameObjectType) 
{ 
    return componentsMap[gameObjectType]; 
} 

在返回對象中的數據丟失了。

+0

存儲「IGameObject *&gameObj」而不是僅存儲指針的更深層的原因是什麼? – Najzero

+0

對象本身將從緩存中調用並保留持久內存,當我嘗試在應用程序中的某處調用對象時 我丟失了所有數據,我需要它持久 – user63898

+0

您無法將「WinFrameObj *」轉換爲'IGameObject *&'出於同樣的原因[你不能將'Derived **'轉換爲'Base **'](http://stackoverflow.com/questions/8026040/)。 – fredoverflow

回答

1

你的問題是這樣的功能

void ComponentMadiator::Register(
    const GameObjectType gameObjectType, 
    IGameObject*& gameObj) 

它可能應該接受非參考

ComponentMadiator::Register(
     const GameObjectType gameObjectType, 
     IGameObject *object) 

或接受const引用的指針。

潛在的問題是,您不能將引用衰減爲臨時引用。

+0

我無法獲得指針,它損失了對象存儲在複本生命週期 – user63898

+0

@ user63898不,參數類型不會影響類似的任何內容。你誤解了有關指針,引用和對象生命週期的內容,但是很難猜出它是什麼。您應該發佈有關您嘗試解決的問題的新問題,而不是您提出的解決方案不起作用的原因。 – molbdnilo

+0

嗯,我試圖解決的主要問題是,對象是以某種方式丟失我設置他們的數據,在某個地方他們走出了scop – user63898

相關問題