問題描述
這是一個有效的表達嗎?如果是這樣,您能否重寫它以使其更有意義?例如,它是否與 (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++ 中的有效語句嗎?如果有,你如何評價?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!