C++带模板的函数在头文件中定义,在源文件中实现为什么老报错

C++语言 码拜 8年前 (2016-06-02) 2946次浏览
这是头文件test.h里的代码:
template <class T>
class test
{
private:
T a,b;
public:
test();
test(T a,T b);
void output();
};
这是源文件test.cpp里的代码:
#include “test.h”
#include <iostream>
using namespace std;
template <class T>
test<T>::test()
{
a=0;
b=0;
}
template <class T>
test<T>::test(T aa,T bb)
{
a=aa;
b=bb;
}
template <class T>
void test<T>::output()
{
cout<<“a=”<<a<<endl;
cout<<“b=”<<b<<endl;
}
主函数main.cpp里的代码:
#include <iostream>
#include “test.h”
using namespace std;
void main()
{
int a,b;
cin>>a>>b;
test<int> tt(a,b);
tt.output();
}
编译错误如下:
1>  test.cpp
1>main.obj : error LNK2019: 无法解析的外部符号 “public: __thiscall test<int>::test<int>(int,int)” (??0?$test@H@@QAE@HH@Z),该符号在函数 _main 中被引用:

C++要求模板的声明和实现对引用者必须都可见,模板的声明和实现要放到一个文件里,都写在.h文件里

卸载退文件里

5

写模板要把声明和实现全部在“.h”中实现,否则就会报错,刚开始学时本人也遇上过这种情况!:)

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明C++带模板的函数在头文件中定义,在源文件中实现为什么老报错
喜欢 (0)
[1034331897@qq.com]
分享 (0)