数据结构基础(10) --单链表迭代器的设计与实现(三)
or->() throw (std::out_of_range); //重载 ++operator ListIterator &operator++() throw (std::out_of_range); //注意:此处返回的是值,而不是reference ListIterator operator++(int) throw (std::out_of_range); bool isEmpty() const; private: const MyList
&list; Node
*currentNode; }; template
const Type &ListIterator
::operator*() const throw (std::out_of_range) { if (isEmpty()) throw std::out_of_range("iterator is out of range"); // 返回当前指针指向的内容 return currentNode->data; } template
Type &ListIterator
::operator*() throw (std::out_of_range) { //首先为*this添加const属性, //以调用该函数的const版本, //然后再使用const_case, //将该函数调用所带有的const属性转除 //operator->()的non-const版本与此类同 return const_cast
( static_cast
&>(*this).operator*() ); } template
const Node
*ListIterator
::operator->() const throw (std::out_of_range) { if (isEmpty()) throw std::out_of_range("iterator is out of range"); //直接返回指针 return currentNode; } template
Node
*ListIterator
::operator->() throw (std::out_of_range) { // 见上 return const_cast
*> ( static_cast
>(*this).operator->() ); } template
ListIterator
&ListIterator
::operator++() throw (std::out_of_range) { if (isEmpty()) throw std::out_of_range("iterator is out of range"); //指针前移 currentNode = currentNode->next; return *this; } template
ListIterator
ListIterator
::operator++(int) throw (std::out_of_range) { ListIterator tmp(*this); ++ (*this); //调用前向++版本 return tmp; } template
bool ListIterator
::isEmpty() const { if (currentNode == NULL) return true; return false; } #endif // MYLIST_H_INCLUDED