为什么我们不能在C ++中进行三向比较? [英] Why can't we do three-way comparison in C++?
问题描述
为了快速总结,为什么 2为什么<x <9
等于 2<x&&x <9
?
To summarize it quickly, why isn't 2 < x < 9
equal to 2 < x && x < 9
?
这是我编写的测试代码:
This is the test code I've written:
#include <iostream>
int main()
{
int nums[] = { 5 , 1, 10};
// We are gonna check if the number is in the range 2 - 9
for (auto e : nums)
{
if (2 < e < 9)
std::cout << "2 < " << e << " < 9" << std::endl;
if(2 < e && e < 9)
std::cout << "2 < " << e << " and " << e << " < 9" << std::endl;
}
std::cin.get();
}
这是我得到的输出:
2 < 5 < 9
2 < 5 and 5 < 9
2 < 1 < 9
2 < 10 < 9
看起来只有 2<e&&e<9
正常工作.
推荐答案
表达式
2 < x < 9
分组为
(2 < x) < 9
并且由于 2<x
为 false
(0)或 true
(1),且两者均小于9,始终为 true
.
And since 2 < x
is either false
(0) or true
(1), and both are less than 9, it's always true
.
因此,除非您对非内置类型 x
使用重载运算符(否则,如果 2
<
的 proxy 对象的实例),如果要测试 x
是否为在(2,9)间隔中,您需要按照自己的方式编写.
So unless you use overloaded operators for a non-built-in type x
(then a 3-way comparison would be possible if 2 < x
were to return an instance of a proxy object on which <
is defined), if you want to test if x
is in the interval (2, 9) you need to write it the way you have.
这篇关于为什么我们不能在C ++中进行三向比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!