模板类不支持分离编译。你需要把所有的申明和定义放在一个文件里实现。
举个例子,cpp_1.h如下:
template<class numtype>
class cpp_1 {
public:
numtype a;
cpp_1(numtype);
}
cpp.cpp如下:
#include "cpp_1.h"
template<class numtype>
cpp_1<class numtype>::cpp_1(numtype x){
a = x;
}
main.cpp如下:
#include "cpp.h"
int main(){
cpp_1<int> s(3); //第三行
return 0;
}
因为模板类不支持分离编译。上面第三行就会报错,编译器在编译cpp的时候不知道要生成cpp_1<int>::cpp_1(int)的代码,所以link的时候就找不到.
因此,正确的方法是,把模板类的声明和实现放在一个文件里。