Is this ? ternary operation legal?(这是 ?三元运算合法吗?)
问题描述
我不是专家,但我喜欢学习和理解.考虑到这一点,我在 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.
这篇关于这是 ?三元运算合法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:这是 ?三元运算合法吗?
基础教程推荐
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01