Does overloading '==' get you '!='?

前端 未结 4 1986
慢半拍i
慢半拍i 2020-12-15 02:27

If I manually overload the == operator for a structure, do I get the != operator for free (presumably defined to be the boolean opposite), or do I

4条回答
  •  孤街浪徒
    2020-12-15 02:52

    No nothing is for free. You pay for what you use in C++(in case of Operator Overloading).
    You only get the Operator which you overload nothing more.

    Also, It is a good practice that if you overload == operator then you should overload != as well because the users of your class will expect that to be available.

    Operator Overloading C++ FAQ should be a good read.


    Answering the updated Question:

    The question is not whether or not I CAN overload both operators, but whether I must overload inequality if I've already overloaded the equality operator.

    NO.
    There is no such requirement that you Must overload != If you need to overload ==. However,it is a good practice that you Should overload operators related to each other.

    Why is it a good practice?
    Think it from the perspective of the user of your class. If the user of your class can use ==(equality criteria) to compare objects of your class, naturally they are going to expect that they should be able to use !=(Non-equality criteria) as well, this stems from the fact that these two operators are related closely and supported for all built-in tyes.

    What happens if you disregard the should and not overload != when you overload ==?
    If the users of your class use != they will get a compile error.
    They would frown a bit about not being provided with != when they are provided with == and they will have to realign their logic to use == instead of the !=.

    So you can live with it but be ready to expect a few frowns and complaints of inconvinience and not providing user friendly interface.

提交回复
热议问题