【问题标题】:Linker error when using a template class? [duplicate]使用模板类时出现链接器错误? [复制]
【发布时间】:2012-02-07 05:39:06
【问题描述】:
   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;
}

【问题讨论】:

    标签: c++ templates inheritance linker-errors


    【解决方案1】:

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

    希望这会有所帮助!

    【讨论】:

    • “但不幸的是它会一直存在”——直到我们得到模块。 *交叉手指*
    • 像魅力一样工作,只需对您的解决方案进行一些修复。我没有在 .h 文件中添加代码,而是在 .h 文件的底部包含了 .cpp 文件。这与两个部分在同一个文件中的结果相同。在“hijo.cpp”#ifndef hijo_cpp #define hijo_cpp 和底部#endif...谢谢你的回答...
    • 需要再等 8 分钟才能将问题标记为已回答
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-23
    • 2015-04-13
    相关资源
    最近更新 更多