在if语句中,cin如何评估为true? [英] How does cin evaluate to true when inside an if statement?

查看:104
本文介绍了在if语句中,cin如何评估为true?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为:

if (true) 
{execute this statement}

那么如果(std :: cin>> X)当没有真实的时候执行为真?我能理解它是否是 if(x <= y) if(y [operator] x),但是什么样的逻辑是istream = true?。

So how does if (std::cin >> X) execute as true when there is nothing "true" about it? I could understand if it was if ( x <= y) or if ( y [operator] x ), but what kind of logic is "istream = true?".

推荐答案

答案取决于标准C ++库的版本:

The answer depends on the version of the standard C++ library:


  • 在C ++ 11之前,内的转换,如果依赖于转换流到 void * 使用 operator void *

  • 从C ++ 11开始转换依赖于 operator bool std :: istream

  • Prior to C++11 the conversion inside if relied on converting the stream to void* using operator void*
  • Starting with C++11 the conversion relies on operator bool of std::istream

请注意 std :: cin>> X 不仅是一个语句,还是一个表达式。它返回 std :: cin 。 链接输入需要此行为,例如 std :: cin>> X>> Y>> ž。当您将输入放在 if 中时,相同的行为会派上用场:结果流传递给 operator bool operator void * ,因此布尔值被送到条件。

Note that std::cin >> X is not only a statement, but also an expression. It returns std::cin. This behavior is required for "chained" input, e.g. std::cin >> X >> Y >> Z. The same behavior comes in handy when you place input inside an if: the resultant stream gets passed to operator bool or operator void*, so a boolean value gets fed to the conditional.

这篇关于在if语句中,cin如何评估为true?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆