我遇到了重载post/pre ++运算符的问题.所以我有我的主类Nodelist,从这个类我有一个打印功能.print函数使用Iterator该类访问++操作符函数.一切正常,直到达到temp++;无限循环为止; 我正在使用这个链接列表,虽然我知道这nodePntr->next可以让我移动到下一个节点我不知道为什么这不起作用?
节点
struct node {
int info;
node* next;
};
Run Code Online (Sandbox Code Playgroud)
节点列表
class NodeList {
public:
void Print();
private:
node* header;
};
void Nodelist::Print()
{
Iterator temp;
temp = header;
while (!temp.isNull()) {
cout << *temp << " ";
temp++;
}
}
Run Code Online (Sandbox Code Playgroud)
迭代器
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;
}
Run Code Online (Sandbox Code Playgroud)
您的增量函数需要返回类型的值Iterator,而不是node,并且应该更新迭代器存储的内部节点.你的循环永远不会实际修改函数中的temp对象Print,因此无限循环.
例如,您的预增量函数可能看起来像这样
Iterator& Iterator::operator ++ ()
{
// Update the node inside the iterator.
nodePntr = nodePntr->next;
// Return a reference to the updated iterator.
return *this;
}
Run Code Online (Sandbox Code Playgroud)
然后你的后增量可以用你的预增量来写
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;
}
Run Code Online (Sandbox Code Playgroud)