【问题标题】:++ operator for a BST ClassBST 类的 ++ 运算符
【发布时间】:2018-03-22 10:49:02
【问题描述】:

我已经创建了一个 BST 类,有一个根节点和左右节点。它运行良好。我正在尝试创建一个 ++ 运算符迭代器,它可以遍历每个节点并增加它的值。这是我到目前为止所得到的,我仍然认为它与我的构造函数有关。下面是我在 BST 类中包含的嵌套 Iterator 类。我只是 cout 看看它是否正常工作,但它一直打印出 0。

class Iterator
{
private:
    // private iterator state...
    nodeptr root;
public:
    Iterator(nodeptr roots_) : root(roots_) {};
    ~Iterator() {}
    bool operator!=(const Iterator& rhs) const { return (this-> root != rhs.root); }
    bool operator==(const Iterator& rhs) const {
        return (this->root == rhs.root);
    }

    Iterator operator++(T) {
      nodeptr ptr = root;
        if (root == NULL)
        {
            cout << "The tree is empty" << endl;
        }
        else
        {
            if (ptr->left != NULL)
            {
                ptr = ptr->left;
            }
            cout << ptr->data << " ";
            if (ptr->right != NULL)
            {
                ptr = ptr->right;
            }
            else
            {
                cout << "_";
            }
        }

        return *this;
    }
}

【问题讨论】:

    标签: c++ c++11 visual-c++ c++14 c++builder


    【解决方案1】:

    无论如何,我不知道迭代器应该在 BST 类中做什么......

    (1) 我不知道operator++ (T) 是什么;据我所知,作为一个类的方法,operator++ 可以带有签名operator++()(前增量)或operator++(int)(后增量);我想您正在尝试定义一个后增量运算符(因为您添加了一个虚拟参数并且因为您返回了Iterator 的副本,而不是引用)但是虚拟参数应该是int 类型,而不是类型T

    (2) 前置增量或后置增量,operator++() 应修改对象;您的操作员不会修改它:它会创建孤独成员 (root) 的本地副本并修改本地副本;对您的operator++(T) 的连续调用应该会产生相同的效果,因为正在做同样的事情;我想你的意图是修改成员root,而不是局部变量ptr

    (3) 假设(存在虚拟参数且返回类型中没有引用)您的意图是创建一个后增量运算符,您必须创建对象的 副本,修改对象并返回 副本;您正在(不是)修改对象并返回对象本身(return *this;),这是预增量运算符的典型行为(在对象中添加一些更改并通过引用返回)。

    为了简单起见,我想你应该写一些东西

    //       v <--- observe the return by reference
    Iterator & operator++ ()
     {
       // something that modify the Iterator object 
    
       // return the object itself as reference
       return *this;
     }
    
    
    // no reference here: return a copy
    Iterator operator++ (int)
     {
       // copy of the object **before** the increment
       // (but you have also to develop a copy constructor)
       Iterator copy { *this };
    
       // pre-increment of the object
       ++(*this);
    
       // return of the before the increment copy
       return copy;
     }
    

    【讨论】:

      猜你喜欢
      • 2011-07-02
      • 1970-01-01
      • 1970-01-01
      • 2011-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-11
      • 2019-09-12
      相关资源
      最近更新 更多