为了教学目的,我一直在尝试实现自己的链表类。
我在迭代器声明中指定了“list”类作为友元,但它似乎没有编译。
这些是我使用的3个类的接口:
节点:
#define null (Node<T> *) 0
template <class T>
class Node {
public:
T content;
Node<T>* next;
Node<T>* prev;
Node (const T& _content) :
content(_content),
next(null),
prev(null)
{}
};
迭代器。
#include "Node.h"
template <class T>
class Iterator {
private:
Node<T>* current;
Iterator (Node<T> *);
public:
bool isDone () const;
bool hasNext () const;
bool hasPrevious () const;
void stepForward ();
void stepBackwards ();
T& currentElement () const;
friend class List<T>;
};
H表
#include <stdexcept>
#include "Iterator.h"
template <class T>
class List {
private:
Node<T>* head;
Node<T>* tail;
unsigned int items;
public:
List ();
List (const List<T>&);
List& operator = (const List<T>&);
~List ();
bool isEmpty () const {
return items == 0;
}
unsigned int length () const {
return items;
}
void clear ();
void add (const T&);
T remove (const T&) throw (std::length_error&, std::invalid_argument&);
Iterator<T> createStartIterator () const throw (std::length_error&);
Iterator<T> createEndIterator () const throw (std::length_error&);
};
这是我一直在尝试运行的测试程序:
特里普
using namespace std;
#include <iostream>
#include "List/List.cc"
int main ()
{
List<int> myList;
for (int i = 1; i <= 10; i++) {
myList.add(i);
}
for (Iterator<int> it = myList.createStartIterator(); !it.isDone(); it.stepForward()) {
cout << it.currentElement() << endl;
}
return 0;
}
当我试图编译它时,编译器会给出以下错误:
iterator.h:26:错误:list_不是模板
iterator.h:在实例化__iterator_时:
trial.cpp:18:从此处实例化
iterator.h:12:错误:结构列表需要模板参数
list.cc:在成员函数__迭代器列表::createStartInterator()const[with t=in t]中:
trial.cpp:18:从此处实例化
迭代器.h:14:错误:迭代器::迭代器(节点*)[具有t=int]是私有的
list.cc:120:错误:在此上下文中
似乎它没有意识到朋友的声明。
我哪里出错了?