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

前端 未结 4 1973
慢半拍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:49

    Overloading operator == does not give you operator !=. You have to do it manually and the canonical way is to implement it in terms of operator == as in !(left == right).

    The semantics of the operators are not dictated by the standard. You could very well overload operator == to mean equality yet overload operator != to something different like addition or even equality again (not that this is a good practice, in fact it should be discouraged. When in doubt, do as the ints do...).[Refer (1) Below]

    On a side note, Boost.Operators can help you provide canonical implementations for operators. There is also std::rel_ops with a canonical implementation for operator !=.

    (1) To know more about it read Three basic rules of operator overloading in C++.

提交回复
热议问题