出于教学目的,我一直在尝试实现自己的链表类。
我在迭代器声明中将“List”类指定为友元,但它似乎无法编译。
这些是我使用过的 3 个类的接口(interface):
Node.h:
#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)
{}
};
Iterator.h:
#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>;
};
List.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&);
};
这是我一直试图运行的测试程序:
trial.cpp
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:错误:“列表”不是模板
Iterator.h:在“Iterator”的实例化中:
trial.cpp:18:从这里实例化
Iterator.h:12:错误:“结构列表”需要模板参数
List.cc:在成员函数'Iterator List::createStartIterator() const [with T = int]'中:
trial.cpp:18:从这里实例化
Iterator.h:14: 错误:'Iterator::Iterator(Node*) [with T = int]' 是私有(private)的
List.cc:120:错误:在此上下文中
似乎它无法识别 friend 声明。 我哪里做错了?
最佳答案
尝试添加前向声明
template <class T> class List;
在 Iterator.h
的开头 -- 这可能是您需要允许 Iterator
类中的 friend
声明工作的地方.
关于c++ - 在模板类中声明模板友元类时出现编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1993482/