涉及模板的未知错误

Unkown error involving templates

本文关键字:未知 错误      更新时间:2023-10-16

这段代码在一个头文件中,头文件本身可以编译得很好。这个想法是,这是一个BST,我应该创建一个迭代器,按顺序遍历它。

我想我已经很好地理解了这一点,但我一定有错误的函数语法。他们在没有给定类型的情况下进行编译,但当给定int等类型时,它表示找不到具有int等的版本。

template <class TKey>
class bst {
  private:
    struct node {
      node() { key=TKey(); link[0]=link[1]=NULL; parent=NULL; }
      operator TKey () { return key; }
      void print();
      TKey key;
      node *link[2];
      node *parent;
    };
  public:
    class iterator {
    public:
    private:
      friend class bst<TKey>;
      node *p;
    };
    iterator begin();
    iterator end();
    TKey operator*(iterator rhs){return rhs.p -> key;}
    bool operator!=(iterator rhs) {return (!(this.p->key==rhs.p->key));}
    void operator++();
    bst() { Troot=NULL; }
    ~bst() { clear(Troot); }
    bool test;
    bool empty() { return Troot==NULL; }
    void clear() { clear(Troot); Troot=NULL; }
    node *prev_node;
    void erase(TKey &key);
    void insert(TKey &key);
    void print_inorder() { print_inorder(Troot); }
    void print_bylevel();
    void print_iterator();
  private:
    void clear(node *);
    node *minmax_key(node *, int);
    node *erase(node *, TKey &);
    node *insert(node *, TKey &);
    void print_inorder(node *);
    node *Troot;
};

这就是阶级的定义。

template <class  TKey>
class bst<TKey>::iterator bst<TKey>::begin(){
    node *temp = Troot;
    while(temp -> link[0])
        temp = link[0];
    cout << temp -> key << endl;
    iterator it;
    it.p = temp;
    return it;
};
template <class TKey>
class bst<TKey>::iterator bst<TKey>::end(){
    iterator it;
    it.p = NULL;
    return it;
};

这些似乎是造成问题的Iterator函数。

bst.h:266:2: error: no match for 'operator!=' in 'it != bst<TKey>::end [with TKey = int]()'
bst.h:266:2: note: candidates are:

并列出了大量候选

然后

bst.h:269:3: error: no match for 'operator++' in '++it'
bst.h: In member function 'bst<TKey>::iterator bst<TKey>::begin() [with TKey = int]':
bst.h:265:22:   instantiated from 'void bst<TKey>::print_iterator() [with TKey = int]'
BST_usage1.cpp:33:19:   instantiated from here
bst.h:70:3: warning: pointer to a function used in arithmetic [-Wpointer-arith]
bst.h:70:3: error: cannot convert 'int(const char*, const char*)throw ()' to 'bst<int>::node*' in assignment

您对operator!=的定义在类bst<T>中,而不是在内部类bst<T>::iterator中。因此,您定义了一个运算符,它在左手边取bst<T>,在右手边取bst<T>::iterator

如果您在内部iterator类中移动运算符定义,您应该会发现它工作正常(或者至少会给出更有用的错误消息)。