問題描述
這是一個(gè)有效的表達(dá)嗎?如果是這樣,您能否重寫它以使其更有意義?例如,它是否與 (4 > y && y > 1)
相同?您如何評(píng)估鏈?zhǔn)竭壿嬤\(yùn)算符?
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)
比較運(yùn)算符 <
和 >
從左到右評(píng)估.
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.
然后將結(jié)果與 1 進(jìn)行比較.
Then the result is compared to 1.
在這種情況下,由于0
或1
永遠(yuǎn)不會(huì)超過1
,整個(gè)語句將始終返回false強(qiáng)>.
In this case, since 0
or 1
is never more than 1
, the whole statement will always return false.
不過有一個(gè)例外:
如果 y
是一個(gè)類并且 >
運(yùn)算符已被重載以執(zhí)行不尋常的操作.然后一切順利.
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;
}
這篇關(guān)于(4 > y > 1) 是 C++ 中的有效語句嗎?如果有,你如何評(píng)價(jià)?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!