问题描述
在中,建议不要重载任何 运营商(罕见,特殊情况除外)。具体来说,它建议:
In the Google C++ Style Guide, the section on Operator Overloading recommends against overloading any operators ("except in rare, special circumstances"). Specifically, it recommends:
小模糊的什么这样的函子会是什么样子,但我的主要问题是,为什么你想为此写自己的函子吗?不能定义运算符<
,并使用标准 std :: less< T>
函数,更简单?
I'm a little fuzzy on what such a functor would look like, but my main question is, why would you want to write your own functors for this? Wouldn't defining operator<
, and using the standard std::less<T>
function, be simpler? Is there any advantage to using one over the other?
推荐答案
除了更基本的类型,小于操作isn'总是微不足道,甚至平等可能因情况而异。
Except for the more fundamental types, the less-than operation isn't always trivial, and even equality may vary from situation to situation.
想象一下,想要为所有乘客分配登机号码的航空公司的情况。这个数字反映了登机的顺序(当然)。现在,什么决定谁谁谁?您可能只是按照客户注册的顺序 - 在这种情况下,小于操作将比较签入时间。您也可以考虑客户为其票证支付的价格 - 小于现在比较票价。
Imagine the situation of an airline that wants to assign all passengers a boarding number. This number reflects the boarding order (of course). Now, what determines who comes before who? You might just take the order in which the customers registered – in that case, the less-than operation would compare the check-in times. You might also consider the price customers paid for their tickets – less-than would now compare ticket prices.
...等等。总而言之,在 Passenger
类上定义运算符<
有乘客在被分类的容器。我认为这是Google警告的。
… and so on. All in all, it's just not meaningful to define an operator <
on the Passenger
class although it may be required to have passengers in a sorted container. I think that's what Google warns against.
这篇关于比较函子类型与运算符<的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!