2012-02-07 57 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