【发布时间】:2014-04-20 15:35:30
【问题描述】:
我在重载后缀“--”运算符时遇到问题。而不是在代码行的末尾调用它,就像这个带有 Integer 类型的简单示例一样:
int test = 5;
cout << test-- << endl; //Output1: 5
cout << test << endl; //Output2: 4
相反,它会立即被调用,而不是在最后。
注意:LinkList 是我使用不同的运算符构建的一个类:
operator+= 将给定数字添加到列表的开头,operator--(int) 删除最后一个数据成员。 operator<< 只是按顺序打印列表。
LinkList l1;
l1+=1;
l1+=2;
l1+=3;
l1+=4;
l1+=5;
cout << l1 << endl; //Output1: 5 4 3 2 1
cout << l1-- << endl; //Output2: 5 4 3 2
cout << l1 << endl; //Output3: 5 4 3 2
我知道我可以通过在cout 命令之后调用运算符来解决它,但是如何使它像整数示例一样工作(其中 output2 应该在 output1 具有相同的输出)?
这里是操作符的功能:
//Deletes the last node
LinkList LinkList::operator--(int){
if(list){ //If the list isn't empty
if(list->NextNode()){ //If there in another node
Node* newLast = (*this)[list_size - 2]; //Store the new last node
delete newLast->NextNode(); //Delete the last node
newLast->InsertNext(NULL);
}//if
else{ //The head is the only node
delete list; //Delete the head
list = NULL; //The list is now empty
}//else
list_size--; //Update the list size
}//if
return *this;
}//end operator--(int)
谢谢
【问题讨论】:
-
算子不叫“last”,它只需要在修改它的对象之前存储并返回它的当前值。这取决于您对后缀
--的实现是否为您的列表执行此操作。我们无法为您提供进一步的帮助,因为您尚未包含您的实施。 -
感谢您的回复。我已经包含了操作员的代码。是否有必要添加任何附加功能(整个代码很长,我认为与本主题无关)?
-
Instead of it being called at the end of the code line这从来没有是被禁止的行为。你从哪里听到的? -
^ 教授们...好的,谢谢,我得到了答案。无需苛刻。
标签: c++ operators operator-overloading