一个奇怪的现象
先看代码
//baohan.h
template <class T>
class A
{
public:
T fun(T);
};
//baohan.cpp
#include "baohan.h"
template <class T>
T A<T>::fun(T n)
{
return n+2;
}
//main.cpp
#include "baohan.h" //<--改变这里
#include "iostream.h"
void main()
{
A<int> a;
cout<<a.fun(3)<<endl;
}
连接处现以下错误
--------------------Configuration: baohan - Win32 Debug--------------------
Compiling...
main.cpp
Linking...
main.obj : error LNK2001: unresolved external symbol "public: int __thiscall A<int>::fun(int)" (?fun@?$A@H@@QAEHH@Z)
Debug/baohan.exe : fatal error LNK1120: 1 unresolved externals
Error executing link.exe.
baohan.exe - 2 error(s), 0 warning(s)
把 #include "baohan.h" //<--改变这里
改成 #include "baohan.cpp" 后连接运行成功得到想要结果
问题是以前不一直是包含头文件就行了吗,难道是用了类模板的原因?
不用类模板时,是只要包含头文件的。