重载的 + 和 - 运算符,难以弄清楚如何检查传入的"amount"是否为负数
overloaded + and - operators, trouble figuring out how to check if the "amount" being passed in is negative
我重载了这些运算符来帮助我遍历一个双链表,但遇到了一个小错误,作为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是否等于零!
相关文章:
- 检查是否以特定精度给出双精度
- 地图计数确实很重要,或者只是检查是否存在
- 检查是否安装了 windows10 C++
- 模板化检查是否存在带有参数列表的类成员函数?
- 如何巧妙地编写两个函数——一个用于检查是否存在解决方案,另一个用于获取所有解决方案
- MPI:检查是否有任何进程已终止
- 给定一个大小为 N 的数组 S,检查是否可以将序列拆分为两个序列
- Vulkan 的传输队列系列功能和显卡支持:条件检查是否准确?
- 如何检查是否定义了固定宽度的整数
- 使用预处理指令检查是否包含标头?
- 在预处理器中检查 g++ 是否使用 -fopenmp 调用
- 将字符串转换为整数类型T,检查是否存在溢出
- C++编译时检查是否可以用某种类型的参数调用重载函数
- 检查是否至少设置了一点而不跳跃
- 在if条件下,右或左改变值的相等性检查是否有任何区别
- C++ 检查是否按下了键,而不是按住了
- 如何在 c++ 中解析包含整数的字符串并检查是否大于最大值
- 检查是否为质数大o
- 检查是否需要 utf8 转换并转换为 utf8
- 如何正确检查 c++ 是否存在注册表项?