我使用模板在c ++代码中实现了一个简单的列表实现。代码是这样的,有两个文件:
TestList.h :
#pragma once
namespace Containers{
template <class T> class TestList
{
public:
TestList();
~TestList();
void Append(T data);
private:
struct Node{
struct Node * next;
T data;
};
int m_count;
Node * m_head;
}
}
TestList.cpp :
#include "TestList.h"
namespace Containers{
template<typename T>
TestList<T>::TestList() : m_count(0), m_head(NULL)
{
}
template<typename T>
TestList<T>::~TestList()
{
if (this->m_head){
Node * tmp = this->m_head;
Node * prev = NULL;
while (tmp->Next){
prev = tmp;
tmp = tmp->next;
delete prev;
}
}
}
template<typename T>
void TestList<T>::Append(T data)
{
Node * tmp = this->m_head;
if (this->m_head){
tmp = this->m_head;
while (tmp->next){
tmp = tmp->next;
}
}
Node * item = new Node();
item->data = data;
if (tmp)
tmp->next = item;
else
this->m_head = item;
this->m_count++;
}
}
所以这是一些小代码,我只是为了玩模板而编写的。然后在main.cpp中:
#include <Windows.h>
#include "TestList.h"
int main()
{
Containers::TestList<const wchar_t *> list;
list.Append(L"123");
return 0;
}
当我尝试编译并运行时,出现如下链接错误:
LNK2019 unresolved external symbol "public: void __thiscall Containers::TestList<wchar_t const *>::Append(wchar_t const *)" (?Append@?$TestList@PB_W@Containers@@QAEXPB_W@Z) referenced in function _main
LNK2019 unresolved external symbol "public: __thiscall Containers::TestList<wchar_t const *>::TestList<wchar_t const *>(void)" (??0?$TestList@PB_W@Containers@@QAE@XZ) referenced in function _main
LNK2019 unresolved external symbol "public: __thiscall Containers::TestList<wchar_t const *>::~TestList<wchar_t const *>(void)" (??1?$TestList@PB_W@Containers@@QAE@XZ) referenced in function _main
所以我在.cpp文件中定义了T,但它仍然给我错误。到目前为止,我在此站点上尝试过建议的解决方案:
输入:
#include "TestList.h"
extern template class Containers::TestList<const wchar_t *>;
extern template Containers::TestList<const wchar_t *>;
extern Containers::TestList<const wchar_t *>;
int main()
{
...