(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;
}

相关文章