C++ 当函数 arg 类型为类接口时,无法传递对指针的引用

C++ Can't pass reference to a pointer when the function arg type is class interface

本文关键字:引用 指针 arg 函数 类型 接口 C++      更新时间:2023-10-16

我的接口看起来像这样:

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* ComponentMadiator::getComponentByObjType(GameObjectType  gameObjectType)
{
    return componentsMap[gameObjectType];
}

返回对象中的数据丢失了。

您的问题是此功能

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

它可能应该接受非参考

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

或接受指针的const引用。

潜在的问题是,您不能将转介到临时引用到非const的引用。