问题描述
我认为:
if (true)
{execute this statement}
那么如果(std :: cin>> X)
当没有真实的时候执行为真?我能理解它是否是 if(x 或
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开始转换依赖于
std :: istream
- Prior to C++11 the conversion inside
if
relied on converting the stream tovoid*
usingoperator void*
- Starting with C++11 the conversion relies on
operator bool
ofstd::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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!