我正在尝试使用多态和从Stack和Queue头文件继承创建LinkedList类。这是我第一次尝试使用模板,但不断出现“已定义类模板”或“不允许抽象类类型”等错误。我如何实现模板,因为我显然做错了?
// LinkedList.h File
#include "Stack.h"
#include "Queue.h"
#include "Node.h"
using namespace std;
template <typename T>
class LinkedList : public Queue<T>, public Stack<T>
{
public:
LinkedList();
~LinkedList(void);
protected:
Node<T> *first;
Node<T> *last;
int numItems;
};
// LinkedList.cpp File
#include "LinkedList.h"
using namespace std;
template <typename T>
class LinkedList
{
LinkedList()
{
first = NULL;
last = NULL;
numItems = 0;
}
LinkedList::~LinkedList(void)
{
while (first != NULL)
{
Node* cur = first;
first = first->next;
delete cur;
}
}
LinkedList::clear() {}
LinkedList::size() {}
// Stack Functions
LinkedList::push(T item) {}
LinkedList::pop() {}
LinkedList::top() {}
// Queue Functions
LinkedList::enqueue(T item) {}
LinkedList::dequeue() {}
LinkedList::peek() {}
}
// Stack.h File (Queue is the same except push/pop/top = enqueue/dequeue/peek)
#pragma once
template <typename T> class Stack
{
public:
virtual ~Stack() {}
virtual int size() = 0;
virtual void clear() = 0;
virtual void push(T item) = 0;
virtual T pop() = 0;
virtual T top() = 0;
};
更新代码
// LinkedList.h File
#pragma once
#include "Stack.h"
#include "Queue.h"
#include "Node.h"
template <typename T>
class LinkedList : public Queue<T>, public Stack<T>
{
public:
LinkedList();
~LinkedList(void);
void clear();
int size();
void push(T item);
T pop();
T top();
void enqueue(T item);
T dequeue();
T peek();
protected:
Node<T> *first;
Node<T> *last;
int numItems;
};
// LinkedList.cpp File
#include "LinkedList.h"
class LinkedList
{
LinkedList::LinkedList()
{
first = NULL;
last = NULL;
numItems = 0;
}
LinkedList::~LinkedList(void)
{
while (first != NULL)
{
Node* cur = first;
first = first->next;
delete cur;
}
}
LinkedList::clear(){}
LinkedList::size(){}
// Stack Functions
void LinkedList::push(T item){}
T LinkedList::pop(){}
T LinkedList::top(){}
// Queue Functions
void LinkedList::enqueue(T item){}
T LinkedList::dequeue(){}
T LinkedList::peek(){}
}
// Stack.h File (Queue is the same except push/pop/top = enqueue/dequeue/peek)
#pragma once
template <typename T> class Stack
{
public:
virtual ~Stack() {}
virtual int size() = 0;
virtual void clear() = 0;
virtual void push(T item) = 0;
virtual T pop() = 0;
virtual T top() = 0;
};
答案 0 :(得分:1)
我看到了
// LinkedList.cpp File
模板定义必须在每个翻译单元上都可见,您不能将它们的定义放在cpp文件中并期望它能够工作(就像它对常规类一样)。所有模板函数的定义都应出现在头文件中。
此外,编译器错误是正确的。您正在编写两个LinkedList
类的定义。我假设你在寻找:
LinkedList::LinkedList(){ ... }