gpt4 book ai didi

c++ - 实现一个链表【C++】编译报错

转载 作者:搜寻专家 更新时间:2023-10-31 01:07:48 25 4
gpt4 key购买 nike

我有以下代码:

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);
}

当我尝试编译时出现以下错误:

error: expected constructor, destructor, or type conversion before ‘List’

在线:

Iterator List<T>::begin() {

我不确定我做错了什么。

最佳答案

Iterator未定义,但 List<T>::Iterator是。您还需要添加 typename :

template<class T>
typename List<T>::Iterator List<T>::begin() { ... };

在这里,typename需要作为歧义器告诉编译器 List<T>::Iterator是一种类型(而不是静态成员)。这在模板化上下文中始终是必需的(参见 here )。

关于c++ - 实现一个链表【C++】编译报错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18875664/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com