[英]Implementing an linked list [C++] compilation error
template <class T>
class List {
public:
class Iterator;
class ConstIterator;
//Constructors and Destructors.
List() : head(NULL), tail(NULL), size(0) {}
List(const List& list);
~List();
//Methods
Iterator begin();
Iterator end();
void insert(const T& data);
void insert(const T& data, const Iterator& iterator);
void remove(const Iterator& iterator);
int getSize() const;
Iterator find();
void sort();
//Operators
List operator = (const List& list);
private:
class Node;
Node* head;
Node* tail;
int size;
};
template <class T>
class List<T>::Node
{
public:
//Constructors and destructors
Node(const T& _data, const Node* _next) : data(_data), next(_next) {}
~Node(); //Destructor
//Methods
//Operators
Node operator = (const Node& node);
private:
T data;
Node* next;
};
template<class T>
class List<T>::Iterator
{
public:
Iterator() : list(NULL), node(NULL){} //Constructor
Iterator(const Iterator& it) : list(it.list), node(it.node) {}
~Iterator(); //Destructor
Iterator& operator=(const Iterator& it);
T& operator * ();
T& operator ++ ();
T operator ++ (int);
T& operator -- ();
T operator -- (int);
bool operator == (const Iterator& iterator) const;
bool operator != (const Iterator& iterator) const;
private:
List<T>* list;
Node* node;
};
template<class T>
class List<T>::ConstIterator
{
public:
ConstIterator() : list(NULL), node(NULL){}
ConstIterator(const ConstIterator& it) : list(it.list), node(it.node) {}
~ConstIterator(); //Destructor
ConstIterator& operator=(const ConstIterator& it);
T& operator * ();
T& operator ++ ();
T operator ++ (int);
T& operator -- ();
T operator -- (int);
bool operator == (const ConstIterator& iterator) const;
bool operator != (const ConstIterator& iterator) const;
private:
const List<T>* list;
const Node* node;
};
template<class T>
Iterator List<T>::begin() {
return Iterator(this, head);
}
When I try to compile I get the following error: 当我尝试编译时,出现以下错误:
error: expected constructor, destructor, or type conversion before ‘List’
On line: 在线:
Iterator List<T>::begin() {
I'm not sure what I'm doing wrong. 我不确定自己在做什么错。
Iterator
is not defined, but List<T>::Iterator
is. 未定义
Iterator
,但定义了List<T>::Iterator
。 You will also need to add typename
: 您还需要添加
typename
:
template<class T>
typename List<T>::Iterator List<T>::begin() { ... };
Here, typename
is required as an ambiguitator to tell the compiler that List<T>::Iterator
is a type (rather than a static member). 在这里,必须使用
typename
作为歧义词,以告知编译器List<T>::Iterator
是一种类型(而不是静态成员)。 This is always required in the templated context (see here ). 在模板化上下文中,这始终是必需的(请参阅此处 )。
if you write the body of the function outside the class declaration, it should be: 如果您在类声明之外编写函数的主体,则应为:
typename List<T>::Iterator List<T>::begin() { ... }
edit: typename added 编辑:添加了typename
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.