为什么不能重载三元运算符? [英] Why is it not possible to overload the ternary operator?

查看:190
本文介绍了为什么不能重载三元运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么不能重载三元运算符'?:'?

Why is it not possible to overload the ternary operator ' ?: '?

我经常使用三元运算符来合并if语句,并且很好奇为什么语言设计者选择禁止该运算符重载.我在 C ++ Operator Overloading 中寻找原因的解释,但没有找到一个解释描述为什么这不可能.脚注提供的唯一信息是它不能被重载.

I use the ternary operator often to consolidate if statements, and am curious why the language designers chose to forbid this operator from being overloaded. I looked for an explanation as to why in C++ Operator Overloading but did not find one describing why this isn't possible. The only information the footnote provides is that it cannot be overloaded.

我最初的猜测是,使操作员超负荷几乎总是会违反上面链接中给出的第一或第二个原则.重载的含义很少是显而易见的,或者会偏离其最初的已知语义.

My initial guess is that overloading the operator will almost always violate number one or two of the principles given in the link above. The meaning of the overload will rarely be obvious or clear or it will deviate from its original known semantics.

所以我的问题更多是为什么这是不可能的,而不是我无法做到的方法.

So my question is more of why is this not possible rather than how, as I know it cannot be done.

推荐答案

我认为当时似乎不值得的主要原因 为该运算符发明新语法的努力. 没有令牌?:,因此您必须创建多个 专门的语法规则. (当前的语法规则 operator后跟一个运算符,该运算符是一个 令牌.)

I think the main reason at the time that it didn't seem worth the effort of inventing a new syntax just for that operator. There is no token ?:, so you'd have to create a number of special grammar rules just for it. (The current grammar rule has operator followed by an operator, which is a single token.)

从经验中我们了解到要使用运算符重载 更合理地说,很明显我们真的不应该 允许&&||的重载,对于 其他回应指出的原因,可能不是 以及运算符逗号(因为重载版本将没有 用户期望的顺序点).所以动机 支持它甚至比原来要少.

As we've learned (from experience) to use operator overloading more reasonably, it has become apparent that we really shouldn't have allowed overloading of && and || either, for the reasons other responses have pointed out, and probably not operator comma as well (since the overloaded versions won't have the sequence point which the user expects). So the motivation to support it is even less than it was originally.

这篇关于为什么不能重载三元运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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