我剛開始使用模板。構造函數鏈接器錯誤使用模板
我想創建一個鏈接列表類,它存儲類型的地址(可能是一個對象)。這裏是我的項目的佈局:
linkedlist.h
node.h
node.cpp
linkedlist.cpp
main.cpp
Node.h
template <class Type> struct Node
{
public:
Node<Type>();
Node<Type>(Type* x = 0, Node* pNext = 0);
Type* data;
Node* next;
};
Node.cpp
#include "node.h"
template<class Type> Node<Type>::Node()
{
next = 0;
data = 0;
}
template<class Type> Node<Type>::Node(Type* item, Node* ptrNext)
{
next = ptrNext;
data = item;
}
linkedlist.h
#include "node.h"
template <class Type> class LinkedList
{
private:
Node<Type>* root;
public:
LinkedList<Type>();
~LinkedList<Type>();
void insert(Type*);
void remove(Type*);
};
linkedlist.cpp
#include "linkedlist.h"
template <class Type> LinkedList<Type>::LinkedList()
{
root = 0;
}
template <class Type> LinkedList<Type>::~LinkedList()
{
Node* p;
while(p = root)
{
root = p->next;
delete p;
}
}
// many more....
在main.cpp中,我有以下幾點:
int main()
{
int *ptrA, *ptrB;
int a = 100, b = 10;
ptrA = &a;
ptrB = &b;
LinkedList<int>myList;
myList.insert(ptrA);
return 0;
}
和編譯器扔連接錯誤:
1>main.obj : error LNK2019: unresolved external symbol "public: __thiscall LinkedList<int>::~LinkedList<int>(void)" ([email protected]@@[email protected]) referenced in function _main
1>main.obj : error LNK2019: unresolved external symbol "public: void __thiscall LinkedList<int>::insert(int *)" ([email protected][email protected]@@[email protected]) referenced in function _main
1>main.obj : error LNK2019: unresolved external symbol "public: __thiscall LinkedList<int>::LinkedList<int>(void)" ([email protected]@@[email protected]) referenced in function _main
嘗試的解決方案:
我改稱爲LinkedListmyList()。這可以解決鏈接器錯誤,但我將無法調用任何成員函數。
如果我放(),myList.insert(ptrA)會說「錯誤:表達式必須有一個類類型」。
很明顯,這是行不通的。
有什麼問題?我認爲整個實施有問題....
感謝您的時間。
可能的重複[爲什麼模板只能在頭文件中實現?](http://stackoverflow.com/questions/495021/why-can-templates-only - 在頭文件中實現) – Flexo 2011-12-20 02:08:32
或http://stackoverflow.com/questions/3705740/c-lnk2019-error-unresolved-external-symbol-template-classs-constructor-and或http:/ /stackoverflow.com/questions/3680312/linker-error-lnk2019 – Flexo 2011-12-20 02:09:55
看起來像一個家庭作業。什麼編譯器? – Geoffroy 2011-12-20 02:10:05