这是 ?三元运算合法吗? [英] Is this ? ternary operation legal?

查看:51
本文介绍了这是 ?三元运算合法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不是专家,但我喜欢学习和理解.考虑到这一点,我在 Arduino IDE 中编写了以下内容:

I'm no expert, but I do like to learn and understand. With that in mind I wrote the following in the Arduino IDE:

lockout[idx] ? bulb[idx].off() : bulb[idx].on();

替换这个:

if (lockout[idx]) bulb[idx].off(); else bulb[idx].on();

lockout[]bool的数组,bulb[]是一个类的数组,.off.on 方法.

lockout[] is an array of bool, and bulb[] is an array of a class, with .off and .on methods.

我四处寻找示例,但从未见过 ? 三元运算符的这种用法.我所读到的似乎是说这不应该奏效.

I've looked around for examples and never seen this usage of the ? ternary operator. And what I've read seems to say that this should not work.

但它确实可以编译.那么这实际上是合法的 C++ 吗?

But it does compile. So is this in fact legitimate C++?

推荐答案

是的,这是合法的 C++.虽然该运算符通常称为 三元运算符,但它在 C++ 标准中称为 条件运算符,并在名为expr.cond"的部分中定义.

Yes, this is legitimate C++. While that operator is commonly called the ternary operator, it is called the conditional operator in the C++ standard, and it is defined in the section named "expr.cond".

C++ 标准明确规定第二个和第三个操作数都可以具有 void 类型.所以标准编写者知道人们可能想使用这个运算符作为编写 if 语句的一种简短方式,就像你正在做的那样.

The C++ standard explicity says it is OK for both the second and third operands to have type void. So the standard writers knew that people might want to use this operator as a short way to write if statements, like you are doing.

如果第二个或第三个操作数的类型不是 void,则标准说尝试将这些操作数中的每一个转换为另一个操作数的类型";它详细说明了这意味着什么.

If the types of the second or third operands are not void, then the standard says "an attempt is made to convert each of those operands to the type of the other" and it goes into detail about what that means.

作为参考,我所指的C++标准版本是N4296,所以它有点旧,但我认为这无关紧要.

For reference, the version of the C++ standard I am referring to is N4296, so it's a little old but I don't think that matters.

这篇关于这是 ?三元运算合法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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