Is (4 gt; y gt; 1) a valid statement in C++? How do you evaluate it if so?((4 gt; y gt; 1) 是 C++ 中的有效语句吗?如果有,你如何评价?)
问题描述
这是一个有效的表达吗?如果是这样,您能否重写它以使其更有意义?例如,它是否与 (4 > y && y > 1)
相同?您如何评估链式逻辑运算符?
Is that a valid expression? If so, can you rewrite it so that it makes more sense? For example, is it the same as (4 > y && y > 1)
? How do you evaluate chained logical operators?
推荐答案
语句 (4 > y > 1)
解析如下:
((4 > y) > 1)
比较运算符 <
和 >
从左到右评估.
The comparison operators <
and >
evaluate left-to-right.
4 >y
返回 0
或 1
取决于它是否为真.
The 4 > y
returns either 0
or 1
depending on if it's true or not.
然后将结果与 1 进行比较.
Then the result is compared to 1.
在这种情况下,由于0
或1
永远不会超过1
,整个语句将始终返回false强>.
In this case, since 0
or 1
is never more than 1
, the whole statement will always return false.
不过有一个例外:
如果 y
是一个类并且 >
运算符已被重载以执行不寻常的操作.然后一切顺利.
If y
is a class and the >
operator has been overloaded to do something unusual. Then anything goes.
例如,这将无法编译:
class mytype{
};
mytype operator>(int x,const mytype &y){
return mytype();
}
int main(){
mytype y;
cout << (4 > y > 1) << endl;
return 0;
}
这篇关于(4 > y > 1) 是 C++ 中的有效语句吗?如果有,你如何评价?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:(4 > y > 1) 是 C++ 中的有效语句吗?如果有


基础教程推荐
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07