重载预增量运算符
Overloading Pre-Increment Operator
声明如下:
Iterator operator++();//pre-increment
定义如下:
LinkedList::Iterator& LinkedList::Iterator::operator++(){
return Iterator(current->next);//this is giving me an error
}
这是 class 的样子
class LinkedList{
public:
Node struct{
/*contains pointer to next node and an integer value*/
int val;
Node* next;
};
class Iterator{
public:
Iterator& operator++();//pre-increment
protected:
Node* current;//points to current node
}
}
您创建了一个 new 迭代器对象,并(尝试)return 对其进行引用。
前缀递增运算符修改this
对象,并且应该return对自身的引用:
current = current->next; // TODO: Add checking for not going out of bounds or dereferencing a null pointer
return *this;
声明如下:
Iterator operator++();//pre-increment
定义如下:
LinkedList::Iterator& LinkedList::Iterator::operator++(){
return Iterator(current->next);//this is giving me an error
}
这是 class 的样子
class LinkedList{
public:
Node struct{
/*contains pointer to next node and an integer value*/
int val;
Node* next;
};
class Iterator{
public:
Iterator& operator++();//pre-increment
protected:
Node* current;//points to current node
}
}
您创建了一个 new 迭代器对象,并(尝试)return 对其进行引用。
前缀递增运算符修改this
对象,并且应该return对自身的引用:
current = current->next; // TODO: Add checking for not going out of bounds or dereferencing a null pointer
return *this;