문제

I have a flimsy understanding of how/why istream can be used in conditionals. I have read this question:(Why istream object can be used as a bool expression?).

I don't understand why this compiles without error…

while (cin >> n) {
    // things and stuff
}

…while this fails to compile (message error: invalid operands to binary expression ('int' and '__istream_type' (aka 'basic_istream<char, std::char_traits<char> >')))

while (true == (cin >> n)) {
    // things and stuff
}
도움이 되었습니까?

해결책

Because the implicit conversion operator of cin is

operator void*() const { ... }

and it can evaluate to zero, so you can check it against zero

while (cin >> x) {}

Conversion operator for bool declared as explicit so your expression will not invoke it:

explicit operator bool(){ ... }

So, you need an explicit cast:

if (true == static_cast<bool>(cin >> a))
{
}

다른 팁

cin >> n returns an istream&. Because the result is used in a comparison, the compiler searches for an operator==(bool, istream), which it cannot find. Therefore, you get an error message.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top