C++ 文件连接问题(VS2005下)
我用C++做一个数据结构的作业,发现编译连接时有问题,简化后发现问题如下:
共有三个文件,BinaryTree.h BinaryTree.cpp main.cpp
BinaryTree.h 文件:
#include <iostream>
using namespace std;
template <typename ElemType>
class BinaryTree
{
private:
ElemType * _root;
void clear();
public:
BinaryTree():_root(0){}
~BinaryTree(){clear();}
};
BinaryTree.cpp 文件:
#include <iostream>
#include "BinaryTree.h "
using namespace std;
template <typename ElemType>
void BinaryTree <ElemType> ::clear()
{
_root=0;
}
main.cpp 文件
#include <iostream>
#include "BinaryTree.h "
int main()
{
BinaryTree <int> BT;
return 0;
}
出现错误情况:
1。编译通过没问题,但build出现错误,如下:
main.obj : error LNK2019: unresolved external symbol "private: void __thiscall BinaryTree <int> ::clear(void) " (?clear@?$BinaryTree@H@@AAEXXZ) referenced in function "public: __thiscall BinaryTree <int> ::~BinaryTree <int> (void) " (??1?$BinaryTree@H@@QAE@XZ)
E:\programming practice\c++\t\Debug\t.exe : fatal error LNK1120: 1 unresolved externals
2。把所有代码放到一个main文件中就可运行
3。如果不用template,直接把BinaryTree的ElemType直接改为int之后,多文件也可以成功build。
请问各位高手,这是什么的问题?关template啥事呢?
[解决办法]
将BinaryTree.cpp的内容放到 BinaryTree.h中
[解决办法]
大概是模板不支持分离编译.类声明和函数定义必须放在一个文件中.
[解决办法]
你可以用模版实例化,在 BinaryTree.cpp 中(所有函数体之外)写:
template BinaryTree <int> ;
这也不是所有编译器都支持的,但是VS2005是支持的。