重载的 + 和 - 运算符,难以弄清楚如何检查传入的"amount"是否为负数

overloaded + and - operators, trouble figuring out how to check if the "amount" being passed in is negative

本文关键字:检查 是否 amount 何检查 运算符 重载 弄清楚      更新时间:2023-10-16

我重载了这些运算符来帮助我遍历一个双链表,但遇到了一个小错误,作为c++的新手,我陷入了困境。我从来没有考虑过——输入的"金额"是负数。所以我想我需要在每个运算符中检查一个负数,因为这将极大地改变我遍历列表的方式,例如,如果我指向节点5和I+(-3),我希望它向后移动三个节点,与-,5-(-3)相同的是向前移动三个节点。逻辑看似简单,但语法却令人困惑。以下是过载的操作员:

template <typename T>
typename doublyLinkedList<T>::iterator doublyLinkedList<T>::iterator::operator+(const int amount) const {
    doublyLinkedList<T>::iterator tempClone(*this);
    tempClone.pastBoundary=false;
    T i;
    for(i=0; i < amount; i++)
    {   
       if(tempClone.current->forward == NULL)
       {
          tempClone.pastBoundary =true;
       }else
       {
          ++tempClone;
       }
    }
    if(tempClone.pastBoundary == true)
    {
       return *this;
    }else
    {
        return tempClone;   
    }
}
template <typename T>
typename doublyLinkedList<T>::iterator doublyLinkedList<T>::iterator::operator-(const int amount) const {
    doublyLinkedList<T>::iterator tempClone(*this);
    tempClone.pastBoundary=false;
    T i;
    for(i=0; i < amount; i++)
       {    
        if(tempClone.current->backward == NULL)
       {
          tempClone.pastBoundary =true;
       }else
       {
          --tempClone;
       }
    }

    if(tempClone.pastBoundary == true)
    {
       return *this;
    }else
    {
        return tempClone;   
    }
}

if(amount = (-amount))-除非amount为0,否则始终为true。

它需要在for循环之前。事实上,我可能会这么做:

if (amount < 0) return this->operator-(-amount); 

对于另一个操作者反之亦然。

在运算符+的开头添加:

if (amount <0) {
  operator-(-amount);
  return;
}

类似地,在操作员中添加:

if (amount <0) {
  operator+(-amount);
  return;
}

编辑:顺便说一句,要小心打字错误,比如:

if(amount = (-amount))

它将-aunt赋给amount,然后测试amount是否等于零!