c++ - 重载后/前增量运算符

标签 c++

我在重载后/前++ 运算符时遇到问题。所以我有我的主类 Nodelist 并且从这个类我有一个打印的函数。 print 函数使用 Iterator 类来访问 ++ 运算符函数。在到达 temp++; 之前一切正常,这会导致无限循环;我将它用于链表,虽然我知道 nodePntr->next 允许我移动到下一个节点,但我不确定为什么这不起作用?

节点

struct node {
    int info;
    node* next;
};

节点列表

class NodeList {
public:
    void Print();
private:
    node* header;
};

void Nodelist::Print()
{
    Iterator temp;

    temp = header;
    while (!temp.isNull()) {
        cout << *temp << " ";
        temp++;
    }
}

迭代器

class Iterator {
public:
    friend class Nodelist;
    Iterator();
    Iterator(node *);
    bool isNull();
    node operator++();
    node operator++(int);
private:
    node* nodePntr;
};

node Iterator::operator++()
{
    node *temp = nodePntr->next;
    return *temp;
}

node Iterator::operator++(int)
{
    node *temp = nodePntr;
    ++temp;
    return *temp;
}

最佳答案

您的增量函数需要返回类型为Iterator 的值,而不是node,并且应该更新迭代器存储的内部节点。您的循环实际上从未修改 Print 函数中的 temp 对象,因此是无限循环。

例如,您的预增量函数可能看起来像这样

Iterator& Iterator::operator ++ ()
{
    // Update the node inside the iterator.
    nodePntr = nodePntr->next;
    // Return a reference to the updated iterator.
    return *this;
}

然后你的后增量可以写成你的前增量

Iterator Iterator::operator ++ (int)
{
    // Make a copy. A working copy constructor is left as an exercise to the reader.
    Iterator temp(*this);
    // Call the pre-increment (code reuse);
    ++(*this); 
    return temp;
}

关于c++ - 重载后/前增量运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23070179/

相关文章:

c++ - 更新一个 QTableView

c++ - #including 前一个目录的头文件 (../)

c++ - 如何在所有派生类中调用重写的方法

c++ - 在类C++中的并集内初始化数组

按属性对对象 vector 进行排序的 C++ 模板

c++ - 如何以 lambda 作为第一个参数覆盖可变参数模板?

c++ - 如何从实体组件系统中的子类访问属性

c++ - 是否有用于限制模板的成语/设计模式?

c++ - 是否可以扩展 "erase–remove"习惯用法以同时处理多个容器?

c++ - 最小化、最大化按钮无缘无故消失