我们正在开发一个自定义List类。我们试图实现迭代器和const_iterator及其函数,但是我们的++运算符有问题。 PostFix完全不起作用,并且当我们步入太远时(当前代码是一个只返回最后有效结果的解决方法),PreFix会给我们分段错误。 问题1:如何修复与前缀相关的段错误而无需返回上一个有效元素? (我们试过返回nullptr)。Iterator和const_iterator操作符++后置和前缀
即使我们已经按照互联网上的每个指南<,Postfix也不会迭代。 <
问题2:PostFix为什么不起作用?
代码交&前缀:
List_const_iterator_& operator++()
{
if(ptr->next_ != nullptr)
{
ptr = ptr->next_;
return *this;
}
else
return *this;
}
List_const_iterator_ operator++(int unused)
{
List_const_iterator_ temp(*this);
if(ptr->next_ != nullptr)
{
ptr = ptr->next_;
return temp;
}
else
return *this;
}
Testcode(大气压下以后缀):
List<int> list1 {324, 2, 3};
List_const_iterator_<int> clst = list1.cbegin();
clst = clst++;
cout << "val: " << clst.ptr->data_ << endl;
clst = clst++;
cout << "val2: " << clst.ptr->data_ << endl;
clst = clst++;
cout << "val3: " << clst.ptr->data_ << endl;
输出为后缀:
val: 324
val2: 324
val3: 324
输出,用于前缀:
val: 2
val2: 3
val3: 3 <-- This is where we segfault if we don't use the controll.
鉴于postfix操作符返回旧值,您对clst = clst ++;(除了未定义的行为)有什么期待? – molbdnilo