简体   繁体   English

三元运算奇怪的行为

[英]Odd behavior with ternary operation

The following code is supposed to remove the last char of a string and append l (lowercase L) if flip is true or r if it's false. 以下代码应该删除字符串的最后一个字符,如果flip为true则附加l (小写L)或如果为false则附加r

std::stringstream ss;
ss << code.substr(0, code.size() - 1);
ss << flip ? "l" : "r";
std::string _code = ss.str();

However, when flip is true, it appends 1 and when it's false, it appends 0 . 但是,当flip为true时,它会追加1 ,当它为false时,它会追加0 How come? 怎么会?

Precedence issue. 优先权问题。

ss << flip ? "l" : "r";

means 手段

(ss << flip) ? "l" : "r";

Use 使用

ss << ( flip ? "l" : "r" );

It has to do with operator precedence. 它与运算符优先级有关。 << has priority over ? <<优先考虑? which means flip is appended onto ss first. 这意味着首先将flip附加到ss

The following should lead to the expected behaviour: 以下应导致预期的行为:

 ss << (flip ? "l" : "r");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM