我正在学习基本的链接列表,并希望尝试编写自己的实现。 但是,我在编译时遇到以下错误:
/tmp/ccNerPXr.o: In function `main':
main.cpp:(.text+0x10): undefined reference to `LinkedList<int>::LinkedList()'
main.cpp:(.text+0x2c): undefined reference to `LinkedList<int>::insert(int const&)'
main.cpp:(.text+0x49): undefined reference to `LinkedList<int>::displayList()'
collect2: error: ld returned 1 exit status
我查看了其他堆栈溢出的答案,但找不到符合我特定问题的答案。模板类的名称与main中的实例声明匹配,我记得#include&#34; LinkedList.h&#34;正确地,我仔细检查以确保* .h中的前向声明与* .cpp中的前向声明匹配。还有什么可能导致此错误?它是在盯着我看,我只是太盲目无法看到它吗?我觉得这可能比我制作的更简单......
这是我的(未完成的)源代码供参考: main.cpp
#include "LinkedList.h"
#include <iostream>
using namespace std;
int main()
{
LinkedList<int> normList;
for(int i = 0; i < 5; i++)
normList.insert(i);
normList.displayList();
return 0;
}
LinkedList.h
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
#include <cstddef>
template <class Object>
class LinkedList
{
struct ListNode
{
Object element;
ListNode *next;
ListNode() : element(0), next(NULL) {};
};
ListNode *head;
ListNode *tail;
public:
LinkedList();
void insert(const Object &x);
void erase(const Object &x);
void eraseList();
void displayList();
};
#endif
LinkedList.cpp
#include "LinkedList.h"
#include <iostream>
using namespace std;
template <class Object>
LinkedList<Object>::LinkedList()
{
head = NULL;
}
/*This function will insert an object
*using the tail-end insertion method
*i.e., inserting at the end of the list
*/
template <class Object>
void LinkedList<Object>::insert(const Object &x)
{
ListNode *newNode = new ListNode(x, NULL);
if( !head ) {
head = newNode;
tail = head;
} else {
tail->next = newNode;
tail = newNode;
}
}//insert()
template <class Object>
void LinkedList<Object>::erase(const Object &x)
{
ListNode *prev;
} //erase()
/*
*Function that deletes entire list
*/
template <class Object>
void LinkedList<Object>::eraseList()
{
ListNode *prev;
while(head->next)
{
prev = head;
delete head;
head = prev->next;
}
}//eraseList()
template <class Object>
void LinkedList<Object>::displayList()
{
if(!head)
cout << "The list is empty\n";
while(head->next)
{
cout << head->element << endl;
head = head->next;
}
} //displayList()
提前感谢任何帮助或输入