[英]overloading post/pre increment operators
我在重載post / pre ++運算符時遇到問題。 因此,我有主類Nodelist
並且從該類中可以輸出一個函數。 打印函數使用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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.