2012-10-08 86 views
1

可能重複:
Why do I get 「unresolved external symbol」 errors when using templates?
「undefined reference」 to a template class function未定義參考<std::string>的std :: string&

我就行錯誤:)控制檯::的getInstance( - > readObjectData(一);在main.cpp中

未定義參照void Console::readObjectData<std::string>std::string&)

Console.h http://pastebin.com/WsQR7JNq

#define CONSOLE_H 
#include <string> 

using namespace std; 

class Console 
{ 
public: 
    static Console* getInstance(); 


    template <typename T> 
    void readObjectData(T& o); 
protected: 
private: 
    Console(); // Private so that it can not be called 
    Console(Console const&);    // copy constructor is private 
    Console& operator=(Console const&); // assignment operator is private 
    static Console* m_pInstance; 


}; 
    #endif // CONSOLE_H 

Console.cpp http://pastebin.com/N02HjgBw

#include "Console.h" 
#include "Log.h" 
#include <iostream> 
#include <sstream> 
#include <string> 

using namespace std; 

// Global static pointer used to ensure a single instance of the class. 
Console* Console::m_pInstance = NULL; 

Console::Console() 
{ 

} 

Console::Console(Console const&) 
{ 

} 

Console& Console::operator=(Console const&) 
{ 

} 

Console* Console::getInstance() 
{ 
if (!m_pInstance) // Only allow one instance of class to be generated. 
    m_pInstance = new Console; 

return m_pInstance; 
} 


template <typename T> 
void Console::readObjectData(T& o) { 
    //cin >> o; 
} 

的main.cpp http://pastebin.com/U6qAJUN1

#include "Console.h" 

using namespace std; 

int main() 
{ 

    string a; 

    Console::getInstance()->readObjectData(a); 
    return 0; 
} 

什麼想法?

+2

編譯器需要查看模板函數的定義,您需要將定義包含在頭文件中。 –

+0

每一天,都有一個關於模板和未定義引用的新問題... – jpalecek

回答

3

不能定義模板<>「在.cpp文件d功能。

移動

template <typename T> 
void Console::readObjectData(T& o) { 
    //cin >> o; 
} 

要頭文件。

2

你沒有實現這個方法。你必須在.h文件中爲你的模板提供實現

2

因爲你還沒有在頭文件中放置readObjectData的實現,所以你需要提供一個明確的函數特化 - 一個需要std :: string & 。

這應該在Console.cpp:

template <> 
void Console::readObjectData(string& o) { 
    //cin >> o; 
} 
1

不能放在Console.cpp模板方法實現它必須出現在頭文件,或者您必須實現明確的分工爲std::string

0

爲模板函數的定義(readObjectData)具有被內聯,而不是在一個cpp文件。 當它看到的一個模板函數或模板類的類的編譯器,讓整個班級的新類型卡在那裏的副本。因此,如果將該函數的定義粘貼到.cpp文件中,編譯器將不知道實現的位置,因爲它不存在。

0

在一些C++文件轉換爲輸出(執行,共享庫或...)的過程2工具將協同操作,即創建目標文件的第一編譯器和鏈接器然後這些對象轉換到輸出。你應該知道的是,鏈接器與模板無關(除了顯式實例化的特殊情況外),模板將由編譯器實例化,另一個註釋是編譯器與源文件中包含的每個源文件和頭文件一起工作,並忽略您項目的所有其他文件。因此,當編譯器想要編譯main.cpp時,它看不到readObjectData的實現,因此它不能在該函數的目標文件中生成任何代碼,並且當鏈接器想要將對象鏈接到結果時,它永遠不會找到該函數的實現!所以最簡單的方法是將readObjectData的實現移動到.h文件,並且每件事情都將按預期工作。