模板
类模板函数的定义可以定义在类体的外部,那我得程序定义在外部有问题,请问是怎么回事?比如Stack.h:
template<class T>class Stack
{ T* date;
public:
Stack(int n);
~Stack();
};
我想把实现写在类外部,即Stack.cpp:
#include "stack.h"
//template<class T> Stack<T>;
template<class T> Stack<T>::Stack(int n)
{
date=new T[n];}
template<class T> Stack<T>::~Stack()
{
delete[] date;
}
这样为什么会出现编译错误:
ompiling...
stack.cpp
Linking...
main.obj : error LNK2001: unresolved external symbol "public: __thiscall Stack<int>::~Stack<int>(void)" (??1?$Stack@H@@QAE@XZ)
main.obj : error LNK2001: unresolved external symbol "public: __thiscall Stack<class complex>::~Stack<class complex>(void)" (??1?$Stack@Vcomplex@@@@QAE@XZ)
main.obj : error LNK2001: unresolved external symbol "public: __thiscall Stack<class complex>::Stack<class complex>(int)" (??0?$Stack@Vcomplex@@@@QAE@H@Z)
main.obj : error LNK2001: unresolved external symbol "public: __thiscall Stack<int>::Stack<int>(int)" (??0?$Stack@H@@QAE@H@Z)
Debug/stack.exe : fatal error LNK1120: 8 unresolved externals
Error executing link.exe.
stack.exe - 5 error(s), 0 warning(s)
而如果我把实现写在类内部就可以编译成功,或者把实现写在Stack.h文件里,但是在累得外部,也不会出问题!这是为什么那?应该怎么把类模板的实现写在另外的文件里?