HoN*_*uRu 6 c++ inheritance templates linker-errors
I'm getting an "unresolved external symbol "public:__thiscall hijo<int>::hijo<int>(void)" referenced in function_main
Run Code Online (Sandbox Code Playgroud)
我开始了一个新项目,因为我在另一个更大的项目上遇到了同样的错误.当我尝试使用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;
}
Run Code Online (Sandbox Code Playgroud)
tem*_*def 11
由于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
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!