gpt4 book ai didi

c++ - C/C++ : How does this inline if get parsed?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:16:10 26 4
gpt4 key购买 nike

考虑这段代码:

int main()
{
cout << true ? "Yes" : "No";
return 0;
}

它的输出将是 1 ,而不是 YesNo。为什么将 true 发送到输出流而不是 YesNo 字符串?内联 if 的其余部分如何解析?

最佳答案

这与操作顺序有关。这与:

  (cout << true) ? "Yes" : "No";

cout << true返回 ostream& ,它必须转换为 bool 或等价物。 ?:的结果被扔掉了。

如果这看起来很奇怪(为什么这个优先级?),请记住 ostream 的 operator<<是 C++ 代码中引入的重载,它不允许更改优先级。 <<的优先级专为对移位有意义的内容而设计。它作为流媒体运营商的使用要晚得多。

编辑:可能转换为 (void*)使用这个:http://www.cplusplus.com/reference/iostream/ios/operator_voidpt/

关于c++ - C/C++ : How does this inline if get parsed?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5977948/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com