使用模板类时链接器错误? [英] Linker error when using a template class?

查看:98
本文介绍了使用模板类时链接器错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

   I'm getting an "unresolved external symbol "public:__thiscall hijo<int>::hijo<int>(void)" referenced in function_main

我开始一个新的项目,因为我在另一个更大的项目上有同样的错误
当我尝试分配空格使用new关键字
如果这个错误是愚蠢的,请原谅我,因为我在最近几个月没有编程任何东西。

I started a new project cause I was having this same error on another larger project. The error occur when I try to allocate space using the new keyword. If this error is silly please forgive me cause I haven't programmed anything in the last months.

  /********************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 ++的奇怪编译模型,你不能分离出.h和.cpp文件非常干净的模板类。具体来说,任何希望使用模板类的翻译单元(C ++源文件)都必须能够访问整个模板定义。这是一个奇怪的语言的奇怪,但不幸的是它在这里留下来。

Due to a weirdness in C++'s compilation model, you cannot separate out .h and .cpp files very cleanly for template classes. Specifically, any translation unit (C++ source file) that wants to use a template class has to have access to the entire template definition. This is a strange quirk of the language, but unfortunately it's here to stay.

一个选择是把实现放在头文件而不是源,没有一个.cpp文件。例如,您可能有此标题:

One option is to put the implementation up in the header file rather than in the source, then to not have a .cpp file at all. For example, you might have this header:

#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

希望这有助于!

这篇关于使用模板类时链接器错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆