您的位置:首页 > 编程语言 > C语言/C++

C++中template的.h文件和.cpp文件的问题

2015-09-24 17:04 246 查看
在C++中,用到类模板时,如果类似一般的类声明定义一样,把类声明放在.h文件中,而具体的函数定义放在.cpp文件中的话,会发现编译器会报错。如类似下面代码:

//test.h文件
#ifndef TEST_H_
#define TEST_H_

template <class T>
class test
{
private:
T a;
public:
test();
};

#endif


//test.cpp文件
#include "test.h"

template <class T>
test<T>::test()
{
a = 0;
}


//main.cpp文件
#include <iostream>
#include "test.h"
using namespace std;

int main()
{
test<int> abc;
}


以上代码在编译时会产生如下错误:

Error    2    error LNK1120: 1 unresolved externals
Error    1    error LNK2019: unresolved external symbol "public: __thiscall test<int>::test<int>(void)" (??0?$test@H@@QAE@XZ) referenced in function _main


原因在于,类模版并不是真正的类,它只是告诉编译器一种生成类的方法,编译器在遇到类模版的实例化时,就会按照模版生成相应的类。

在这里就是编译器遇到main函数中的test<int> abc;时就会去生成一个int类型的test类。

而每一个cpp文件是独立编译的,那么如果将类模版的成员函数单独放在一个cpp文件中,编译器便无法确定要根据什么类型来产生相应的类,也就造成了错误。

一般的解决方法就是将类模版中的成员函数定义也写入.h文件中。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: