【问题标题】:Postfix operator not being called last后缀运算符没有被最后调用
【发布时间】: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&lt;&lt; 只是按顺序打印列表。

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


【解决方案1】:

您首先需要创建当前列表的副本,然后更改当前列表。并且必须退回副本。 在您的示例中,您返回已更改列表的副本。

还要考虑到,当您使用重载运算符函数时,不会像使用内置运算符那样产生副作用。

例如,如果复制构造函数有效,则该函数可能看起来像

//Deletes the last node
LinkList LinkList::operator--(int){
    LinkList currentList( *this );

    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 currentList;
}//end

【讨论】:

  • 谢谢。显然我生活在一个“它自己最后被调用”的谎言中。
猜你喜欢
  • 2016-06-28
  • 2022-11-24
  • 2011-03-12
  • 1970-01-01
  • 1970-01-01
  • 2013-07-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多