只要我不調用該函數,一切都很好,但一旦我調用函數,我得到一個無法解析的外部符號。我所有的類都在SSE命名空間(我自己的)中,並且直到現在都工作得很好。讓我展示。C++無法解析的外部符號與模板函數調用
#include "SDL.h"
#include "Game.h"
#include "GameObject.h"
#include <tchar.h>
SSE::Game Pong;
int _tmain(int argc, char* argv[])
{
SSE::GameObject* object;
Pong.Initialize("Pong!");
object = Pong.Objects().ObjectCreate<SSE::GameObject>();
while (!Pong.bQuit)
{
Pong.Update();
Pong.Draw();
}
return 0;
}
這就是我所說的功能。遊戲是一個爲我運行幕後工作的類(對於這個類一切都很好),Game.Objects()返回Game的ObjectManager,它負責創建和刪除對象以及爲對象提供它們的組件。 ObjectCreate是一個模板函數,它返回一個指向創建的新對象的指針。
從的ObjectManager的.cpp文件:
template <class G>G* ObjectManager::ObjectCreate()
{
ObjectList* tempObjList;
tempObjList = new tempObjList();
tempObjList->objectType = G->ClassName();
tempObjList->objectTypeNumber = 0;
for (unsigned int i = 0; i < v_objList.size(); i++;)
{
if (v_objList[i]->objectType == tempObjList->objectType)
tempObjList->objectTypeNumber++;
}
tempObjList->gameObject = new G(tempObjList->objectType + "_" + tempObjList->objectTypeNumber);
v_objList.push_back(tempObjList);
if (v_objList.back() != tempObjList)
{
delete tempObjList;
return NULL;
}
return v_objList.back();
}
這爲新遊戲物體分配一個唯一的名稱,並在內存中創建它,然後將其存儲到載體中。還有一件事要提到的是,我已經爲許多類似於這個的ObjectManager和GameObject函數獲得了這個無法解析的外部符號錯誤,但是隻有在我以代碼的形式調用它們時纔會這樣做。
僅供參考,錯誤是: 錯誤2錯誤LNK2019:無法解析的外部符號「public:class SSE :: GameObject * __thiscall SSE :: ObjectManager :: ObjectCreate(void)」(?? $ ObjectCreate @ VGameObject @ SSE @@@ ObjectManager @ SSE @@ QAEPAVGameObject @ 1 @ XZ)在函數_SDL_main中引用C:\ SDL \ SimpleStateEngine \ SSE \ main.obj SSE
讓我知道如果您需要其他任何東西,我一直在搜索用了幾個小時。
假設我說的有問題,我是否應該在我的GameObject類中取出模板化的函數,並將GameObject類本身作爲模板類? – 2013-03-13 02:53:34
看到我的答案。你需要在'_tmain'之前的某個頭文件中定義它。 – 2013-03-13 02:55:43
設計是好的。只需從ObjectManager.cpp中將定義'模板 G * ObjectManager :: ObjectCreate()'移動到ObjectManager.h。 –
aschepler
2013-03-13 13:10:29