Linker error when using a template class? [duplicate]

你离开我真会死。 提交于 2020-02-15 07:39:46

问题


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

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;
}

回答1:


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.

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

Hope this helps!



来源:https://stackoverflow.com/questions/9171494/linker-error-when-using-a-template-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!