【问题标题】:Trying to overload operator++, cannot call member function without object试图重载operator++,不能调用没有对象的成员函数
【发布时间】:2016-04-15 14:24:21
【问题描述】:

对不起,如果格式有点不对,我是新来的。我也尝试搜索解决方案,但找不到有效的解决方案。

我正在尝试为二叉搜索树类创建迭代器。非常粗略,我的代码看起来像

template<class Key, class Value>
class BST {
  protected:
    //stuff
  public:
    //stuff
    class iterator {
      public:
        //member functions
        iterator& operator++() {
          //gets next node
        }
    }
}

所以在我的主函数中,我创建了一个迭代器

BST<string, int>::iterator it = bst.begin()

它有效。我可以使用迭代器访问节点。但是当我尝试下一行时

it++;

我得到编译器错误,说我“不能调用成员函数......没有对象”。我不明白为什么不呢?如果我在'it'上调用operator++,它不应该只对'it'进行操作吗?

【问题讨论】:

  • 你重载的操作符是前增量使用:iterator&amp; operator++(int) 后增量。

标签: c++ iterator overloading operator-keyword


【解决方案1】:

后缀增量运算符重载需要在其签名中使用虚拟 int 参数 - 以将其与前缀增量区分开来。像这样:

   iterator operator++(int ) {
      //gets next node
    }

您通常还从后缀增量返回一个值,而不是引用,因为您应该返回预增量的对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-06
    • 2014-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-15
    • 1970-01-01
    相关资源
    最近更新 更多