我在重载后/前++ 运算符时遇到问题。所以我有我的主类 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/