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

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

问题描述

为什么不可能在C ++中重载三元运算符??我经常使用三元运算符来巩固if语句,我很好奇为什么语言设计者选择禁止这个运算符重载。我查找了关于为什么在 C ++操作符重载,但没有找到一个解释描述为什么这是不可能的。脚注提供的唯一信息是它不能被重载。

Why is it not possible to overload the ternary operator ' ?: ' in C++? 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.

推荐答案

我认为当时的主要原因, b $ b为该操作符发明一个新语法的努力。
没有标记?:,所以你必须为它创建一些特殊的语法规则
。 (当前语法规则
具有运算符后跟运算符,它是单个
令牌。)

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.

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

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