我正在尝试创建一个具有多态性和继承自 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;
};