2016-06-13 127 views
1

我正在尝试为二叉搜索树实现迭代器。我被要求不要在我的迭代器中使用任何STL。我只需要覆盖运营商:++,operator*!=。我在operator*错误:“没有*operator匹配这个操作数,操作数类型是*iterator<std::string>”。我正在使用模板库,所以我不确定它为什么不起作用。二叉搜索树inorder迭代器C++

这里是我的代码:

template <typename T> 
class Iterator : public std::iterator<std::forward_iterator_tag, { 

public: 
    Iterator(TreeNode<T>* root) 
    { 
     this->current = root; 
    } 

    template <typename T> 
    bool operator!=(Iterator<T> const & other) const 
    { 
     return this->current != other.current; 
    } 

    template <typename T> 
    T &operator*() const { 
     return current->element; 
    } 


    Iterator operator++() 
    { 
     current = current->nextInorder(); 
     return *this; 
    } 

    Iterator operator++(int dummy) 
    { 
     TreeNode<T> temp = current; 
     current = current->nextInorder(); 
     return *temp; 
    } 

private: 
    TreeNode<T>* current; 
    void nextInorder() 
    { 
     if (current->element == NULL)return; 
     else { 
      nextInorder(current->left); 
      nextInorder(current->element); 
      nextInorder(current->right); 
     } 
    } 

}; 

回答

0

的代码是没有得到很好的粘贴(见class Iterator...线)。 我会建议在bool operator!=(Iterator<T> const & other) constT &operator*() const方法上删除template <typename T>。因为T是用于类实例化的。