(4 > y > 1) 是 C++ 中的有效语句吗?如果有,你如何评价?

2023-02-13C/C++开发问题
4

本文介绍了(4 > y > 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 返回 01 取决于它是否为真.

The 4 > y returns either 0 or 1 depending on if it's true or not.

然后将结果与 1 进行比较.

Then the result is compared to 1.

在这种情况下,由于01永远不会超过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 &gt; y &gt; 1) 是 C++ 中的有效语句吗?如果有,你如何评价?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6