我正在实施一个列表(只是为了好玩):
#include <iostream>
template <class T>
class list {
private:
struct node {
T data;
struct node *next, *prev;
} head;
unsigned int length;
public:
class iterator {
private:
node *ptr;
public:
iterator ();
inline T& operator *();
inline iterator operator ++();
inline iterator operator ++(int);
inline iterator operator --();
inline iterator operator --(int);
};
list ();
//~list ()
inline unsigned int size () const;
inline bool empty () const;
inline iterator begin ();
inline iterator end ();
inline T& front ();
inline T& back ();
//void insert (iterator position, const T &x);
//void push_back (const T &x);
//void push_front (const T &x);
//void pop_back ();
//void pop_front ();
};
template <class T>
inline list<T>::iterator::iterator () {
ptr = NULL;
}
template <class T>
inline T& list<T>::iterator::operator*() {
return ptr->data;
}
template <class T>
inline iterator list<T>::iterator::operator++() {
ptr = ptr->next;
return *this;
}
template <class T>
inline iterator list<T>::iterator::operator++(int) {
iterator tmp = ptr;
ptr = ptr->next;
return tmp;
}
template <class T>
inline iterator list<T>::iterator::operator --() {
ptr = ptr->prev;
return *this;
}
template <class T>
inline iterator list<T>::iterator::operator --(int) {
iterator tmp = ptr;
ptr = ptr->prev;
return tmp;
}
////////////////////
////////////////////
template <class T>
inline list<T>::list () {
head.next = &head;
head.prev = &head;
length = 0;
}
template <class T>
inline unsigned int list<T>::size () const {
return length;
}
template <class T>
inline bool list<T>::empty () const {
return length == 0;
}
template <class T>
inline iterator list<T>::begin () {
return head->next;
}
template <class T>
inline iterator list<T>::end () {
return &head;
}
template <class T>
inline T& list<T>::front () {
return *begin();
}
template <class T>
inline T& list<T>::back () {
return *(--end());
}
我收到了这个错误:
list.h:64: error: expected initializer before ‘list’
list.h:72: error: expected initializer before ‘list’
list.h:81: error: expected initializer before ‘list’
list.h:89: error: expected initializer before ‘list’
list.h:125: error: expected initializer before ‘list’
list.h:132: error: expected initializer before ‘list’
不,我没有错过分号。
有什么想法吗?
答案 0 :(得分:2)
因为您的定义是类外的,所以嵌套类型迭代器不在范围内;您需要限定对iterator
template <class T>
inline iterator list<T>::iterator::operator++() {
应该是
template <class T>
inline typename list<T>::iterator list<T>::iterator::operator++() {