2012-02-07 25 views
5
I'm getting an "unresolved external symbol "public:__thiscall hijo<int>::hijo<int>(void)" referenced in function_main 

我開始了一個新的項目,因爲我在另一個更大的項目上遇到了同樣的錯誤。 當我嘗試使用new關鍵字分配空間時發生錯誤。 如果這個錯誤是愚蠢的,請原諒我,因爲我在過去的幾個月裏沒有編程任何東西。使用模板類時鏈接器錯誤?

/********************file hijo.h******************/ 
#pragma once 
#ifndef hijo_h 
#define hijo_h 

template <class A> 
class hijo 
{ 
public: 
    hijo(void); 
    ~hijo(void); 
}; 
#endif 


    /********************file hijo.cpp***************/ 
    #include "hijo.h" 
#include <iostream> 
using namespace std; 

template <class A> 
hijo<A>::hijo(void) 
{ 
} 
template <class A> 
hijo<A>::~hijo(void) 
{ 
} 
    /*********************at main() function ***************/ 

#include <iostream> 
#include "hijo.h" 

int main(){ 

    hijo<int> *h = new hijo<int>; <---- PROBLEM AT THIS LINE 

    system("pause"); 
    return 0; 
} 

回答

10

由於C++的編譯模型的怪事,你不能爲模板類分離出來的.h和.cpp文件非常乾淨。具體而言,任何想要使用模板類的翻譯單元(C++源文件)都必須能夠訪問整個模板定義。這是一種奇怪的語言怪癖,但不幸的是它留在這裏。

一種選擇是將實現放在頭文件而不是源文件中,然後根本就沒有.cpp文件。例如,你可能有這個標頭:

#pragma once 
#ifndef hijo_h 
#define hijo_h 

template <class A> 
class hijo 
{ 
public: 
    hijo(void); 
    ~hijo(void); 
}; 

/* * * * Implementation Below This Point * * * */ 

template <class A> 
hijo<A>::hijo(void) 
{ 
} 
template <class A> 
hijo<A>::~hijo(void) 
{ 
} 

#endif 

希望這有助於!

+0

「但不幸的是它留在這裏」 - 直到我們獲得模塊。 \ *穿過手指* – Xeo 2012-02-07 05:43:51

+0

工作就像一個魅力,只需要對您的解決方案做一點修復。 而不是添加.h文件中的代碼,我只是將.cpp文件包含在.h文件的底部。 這就好像兩個部分都在同一個文件中一樣。 在 「hijo.cpp」 的#ifndef hijo_cpp 的#define hijo_cpp 並在底部 #ENDIF ... 感謝ü的回答... – HoNgOuRu 2012-02-07 05:44:29

+0

得等到8分多鐘,以紀念這個問題作爲回答 – HoNgOuRu 2012-02-07 05:45:52