为什么我们不能覆盖`||`和`&&`? [英] Why can't we override `||` and `&&`?

查看:92
本文介绍了为什么我们不能覆盖`||`和`&&`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大卫·布莱克(David A. Black)在他的书中说:

[T]条件赋值运算符||=,以及它很少发现的 表亲& =,两者都提供与伪运算符方法相同的快捷方式,但是它们基于运算符,即||&&,您无法覆盖它们.

[T]he conditional assignment operator ||=, as well as its rarely spotted cousin &&=, both of which provide the same kind of shortcut as the pseudooperator methods but are based on operators, namely || and &&, which you can’t override.

他为什么特别提到我们不能覆盖||&&?

Why did he specifically mention that we can't override || and &&?

推荐答案

布尔运算符是对象语言的一部分,与对象上的其他某些运算符在逻辑上可以依赖类的行为不同.当您有一个像==这样的运算符时,可以说该运算符的行为取决于对象的类型,这是合乎逻辑的.字符串应该逐个字符地检查字符,按键值元组检查哈希键值元组,等等.但是,&&||的行为基于语言的定义true和否,不是任何特定于对象的.如果该语言允许您重写这些运算符,则可能没有一致的布尔模型,并且这些运算符将变得完全无用.

Unlike some other operators on objects, who's behavior logically can depend on class, the boolean operators are part of the language. When you have an operator like, say, ==, it is logical to say that the behavior of this operator depends on the type of object. A string should check character by character, a Hash key-value tuple by key-value tuple, etc. However, the behavior of && and || are based on the language's definition of true and false, not anything object specific. If the language allowed you to override these operators, there could be no consistent boolean model, and these operators would become completely useless.

此外,还有性能方面的考虑.因为&&||短路运算符,这意味着,如果说&&的第一个参数的计算结果为false,则甚至不会计算第二个参数.使用||时,如果第一个评估为true,则永远不会评估第二个.如果您可以覆盖这些运算符,则此行为将是不可能的,因为在Ruby中,运算符会作为方法重载.在调用该方法之前,必须根据定义对所有参数进行求值.因此,丧失了性能提高和短路操作员的编程便利性.

Additionally, there is a performance consideration too. Because && and || are short circut operators, which means that if the first argument to, say, &&, evaluates to false, the second one is never even evaluated. With ||, if the first evaluates to true, the second is never evaluated. This behavior would not be possible if you could override these operators, as in Ruby operators are overloaded as methods. And all parameters must be evaluated, by definition, before the method is called. So, the performance boost, and programming convenience of a short circuit operator is lost.

这篇关于为什么我们不能覆盖`||`和`&&`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆