【问题标题】:Overloading Pre-Increment Operator重载预增量运算符
【发布时间】:2020-05-03 18:15:47
【问题描述】:

声明如下:

 Iterator operator++();//pre-increment

这是定义:

LinkedList::Iterator& LinkedList::Iterator::operator++(){
   return Iterator(current->next);//this is giving me an error
}

这是班级的样子

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
    }
} 

【问题讨论】:

  • This operator overloading canonical implementation reference 可能会有所帮助。特别是关于递增和递减运算符的部分。顺便说一句,老实说,任何体面的教科书或教程都应该向您展示正确的方法。这也有助于从逻辑上思考:增量和减量运算符修改了什么?
  • 实现意义不大。通常期望增量运算符具有修改它所调用的对象的副作用;但你的没有。事实上,我认为它甚至不会编译 - 它试图通过引用返回一个临时值。
  • 你说得对,它是临时的,我试图修复它,但是如果我尝试创建一个迭代器对象,我会返回一个本地值。相反,我会收到警告,

标签: c++ c++11 linked-list operators overloading


【解决方案1】:

您创建一个 new 迭代器对象,并(尝试)返回对它的引用。

前缀-增量运算符修改this对象,并应返回对自身的引用:

current = current->next;  // TODO: Add checking for not going out of bounds or dereferencing a null pointer
return *this;

【讨论】:

  • TODO 是可选的顺便说一句,auto it = std::end(my_vector); ++it; 是 UB。
猜你喜欢
  • 2017-06-30
  • 2019-09-25
  • 1970-01-01
  • 2010-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-13
相关资源
最近更新 更多