0
我正在读一本关于数据结构的书,现在正试图实现单链表数据结构。在实施迭代器,我所遇到过载的前缀和后缀增量的这些实现:前缀和后缀增量运算符在C++中为迭代器重载实现之间的区别
iterator &operator++()
{
this->current = this->current->next;
return *this;
}
iterator &operator++(int)
{
iterator old = *this;
++(*this);
return old;
}
我知道,第一个是前缀,第二个是为后缀,但我还没有明白是为什么重载后缀增量有不同的代码?如果我这样做会怎么样?
iterator &operator++(int)
{
this->current = this->current->next;
return *this;
}
在此先感谢。
我认为第一个是返回一个副本 – 2013-03-11 18:56:17
为什么是第一个版本不对? – 2013-03-11 18:57:11
@KudayarPirimbaev:不,请注意声明中的'&'(“iterator&operator ++”)。它返回一个局部变量的引用,因此具有未定义的行为。 – thiton 2013-03-11 18:57:15