2014-02-16 11 views
1

我有地圖,看起來像這樣:的std :: make_shared給出錯誤我不明白

typedef std::map<PuzzlePartLocation, std::shared_ptr<PuzzleObj>> ComponentsMap; 

現在我試着通過溫控功能設置此地圖元素是這樣的:

void ComponentMadiator::Register(const PuzzlePartLocation puzzlePartLocation,PuzzleObj* puzzleObj) 
{ 
    componentsMap[puzzlePartLocation] = std::make_shared<PuzzleObj>(puzzleObj); 
} 

我只是這樣稱呼它:

PuzzleObj* pPuzzleObjStickLeft = new PuzzleObj() 
pComponentMadiator->Register(1,pPuzzleObjStickLeft); 

PuzzleObj包含類型IImageComponent memeber *
PuzzleObj從基類

繼承,但它給我的錯誤是這樣的:

1>c:\program files\microsoft visual studio 11.0\vc\include\memory(873): error C2664: 'PuzzleObj::PuzzleObj(IImageComponent *)' : cannot convert parameter 1 from 'PuzzleObj *' to 'IImageComponent *' 
1>   Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast 
1>   c:\program files\microsoft visual studio 11.0\vc\include\memory(972) : see reference to function template instantiation 'std::_Ref_count_obj<_Ty>::_Ref_count_obj<PuzzleObj*&>(_V0_t)' being compiled 
1>   with 
1>   [ 
1>    _Ty=PuzzleObj, 
1>    _V0_t=PuzzleObj *& 
1>   ] 
1>   c:\program files\microsoft visual studio 11.0\vc\include\memory(972) : see reference to function template instantiation 'std::_Ref_count_obj<_Ty>::_Ref_count_obj<PuzzleObj*&>(_V0_t)' being compiled 
1>   with 
1>   [ 
1>    _Ty=PuzzleObj, 
1>    _V0_t=PuzzleObj *& 
1>   ] 
1>   d:\dev\cpp\cocos2d-x\cocos2d-x-3.0beta2\cocos2d-x-3.0beta2\projects\neonbreaker\classes\componentmadiator.cpp(23) : see reference to function template instantiation 'std::shared_ptr<_Ty> std::make_shared<PuzzleObj,PuzzleObj*&>(_V0_t)' being compiled 
1>   with 
1>   [ 
1>    _Ty=PuzzleObj, 
1>    _V0_t=PuzzleObj *& 
1>   ] 
+0

如果您打算複製'puzzleObj'在'ComponentMadiator :: Register',你需要'的std :: make_shared (* puzzleObj);' < - 引用指針 – dyp

+0

爲什麼你能解釋一下? – user63898

+0

'PuzzleObj'有一個帶'IImageComponent *'的構造函數,對不對? – jrok

回答

1

std::make_shared<PuzzleObj>爲您創建一個新的PuzzleObj。你需要的是std::shared_ptr<PuzzleObj>(puzzleObj)。因爲它通過將其存儲在容器中的股份所有權puzzleObj

void ComponentMadiator::Register(const PuzzlePartLocation puzzlePartLocation, std::shared_ptr<PuzzleObj> const& puzzleObj); 

,並必須在函數的接口進行通信:

更重要的是

void ComponentMadiator::Register(const PuzzlePartLocation puzzlePartLocation,PuzzleObj* puzzleObj); 

應聲明爲。

,並調用它像這樣:

std::shared_ptr<PuzzleObj> pPuzzleObjStickLeft(std::make_shared<PuzzleObj>()); 
pComponentMadiator->Register(1, pPuzzleObjStickLeft); 
+0

的基類它給了我這個錯誤: 1> d:\ dev \ cpp \ cocos2d-x \ cocos2d-x-3.0beta2 \ cocos2d-x-3.0beta2 \ projects \ neonbreaker \類\ helloworldscene.cpp(92):錯誤C2664:'ComponentMadiator :: Register':無法將參數2從'PuzzleObj *'轉換爲'const std :: shared_ptr <_Ty>&' – user63898

+0

@ user63898爲您添加調用代碼示例。 –