使用模板类时出现链接错误?

7
   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;
}
1个回答

13
由于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

希望这能帮到您!

“但不幸的是,它会一直存在” - 直到我们获得模块。 交叉手指 - Xeo
运行得非常好,只需对您的解决方案进行一些修复。我只是在.h文件的底部包含了.cpp文件,而不是将代码添加到.h文件中。 这与将两个部分放在同一个文件中产生相同的结果。在"hijo.cpp"中#ifndef hijo_cpp #define hijo_cpp并在底部#endif... 感谢您的回答... - HoNgOuRu
还需要等待8分钟才能将问题标记为已回答。 - HoNgOuRu
在定义模板函数的cpp文件末尾添加对精确类型的显式特化也可以起作用。然而,应该将此技术的使用限制在小型模块/项目中。 - Alok Save

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接