Postfix运算符最后没有被调用

时间:2014-04-20 15:35:30

标签: c++ operators operator-overloading

我有一个问题,即重载后缀' - '运营商。而不是在代码行的末尾调用它,就像这个带有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)

谢谢

1 个答案:

答案 0 :(得分: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