What is the minimum set of operators I need to overload?

本小妞迷上赌 提交于 2020-01-03 04:29:05

问题


which operators of the comparison (<=, >, ==, etc.) do You usually implement as your basic operators, which You can after use to implement the rest comparison operators or to make all possible comparisons among the classes?


回答1:


You can implement all six of the operators in terms of == and < using the following equivalencies:

a != b    =>    !(a == b)
a > b     =>    b < a
a >= b    =>    !(a < b)
a <= b    =>    !(b < a)



回答2:


I normally implement operator== for objects and also operator!=. Many objects do not have a collating sequence, so the comparison operators <, <=, >, >= do not make sense.

Also, by using boost::equality_comparable and boost::less_than_comparable only operator== and operator< need to be implemented. These can be found in boost/operators.hpp.

Also, I have learned that placing comparison operators in base clases or interface classes can become quite tricky as they allow Descendent_A to be compared to Descendent_B, which are two different descendent classes.

Comparison operators should be implemented as needed in classes. Many classes do not need them. Also, beware of implementing them or defining them in base classes without considering the ramifications of inheritance.




回答3:


For classes where they are applicable I usually implement operator< and operator== "natively" because of their prominence in standard algorithms and containers.

I then implement the other four in terms of these.

Another approach that I sometimes consider is implementing a "compare" function that returns 1, 0, or -1 in the style of strcmp and the implement all the other operators in terms of this. I only do this if operator< and operator== look like they need to share much of the same code which seems to happen less often that I think.



来源:https://stackoverflow.com/questions/4589353/what-is-the-minimum-set-of-operators-i-need-to-overload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!