Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 have to overload it manually (even if to just return !(this == rhs)?

Edit-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. Regardless, good answers have been given.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
212 views
Welcome To Ask or Share your Answers For Others

1 Answer

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++.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...