【发布时间】:2012-06-03 20:11:02
【问题描述】:
可能重复:
Why should the implementation and the declaration of a template class be in the same header file?
Do template class member function implementations always have to go in the header file in C++?
我在这里犯了一些愚蠢的错误,但我看不出是什么。
编译:
//start of header.h
namespace ns
{
class A
{
public:
template <class t>t func();
};
template<class t> t A::func()
{
t a;
return a;
}
}
//end of header.h
//imp.cpp的开始
//imp.cpp 结束
但以下不是:
//start of header.h
namespace ns
{
class A
{
public:
template <class t>t func();
};
}
//end of header.h
//start of imp.cpp
#include "header.h"
using namespace ns;
template<class t> t A::func()
{
t a;
return a;
}
//imp.cpp 结束
错误是: 错误 LNK2019:函数 _main 中引用的未解析外部符号“public: int __thiscall ns::A::func(void)”(??$func@H@A@ns@@QAEHXZ)
【问题讨论】:
-
这不是编译器错误,而是链接器错误。