Я только начал использовать шаблон.Ошибка компоновщика компоновщика с использованием шаблона
Я хочу создать класс связанного списка, который хранит адрес Type (может быть объектом). Вот схема моего проекта:
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 -be-implement-in-the-header-file) – Flexo
или http://stackoverflow.com/questions/3705740/c-lnk2019-error-unresolved-external-symbol-template-classs-constructor-and или http://stackoverflow.com/questions/3680312/linker-error-lnk2019 – Flexo
Кажется, домашнее задание. Какой компилятор? – Geoffroy