Why we can use "while(cin >> a)"
Moderator: Board moderators
Why we can use "while(cin >> a)"
I read some manual and find that the operator >> returns *this, the type should be istream&. Then why can we put it in the while statement as a condition?
-
- Guru
- Posts: 584
- Joined: Thu Jun 19, 2003 3:48 am
- Location: Sanok, Poland
- Contact:
Where is the operator defined? The class hierarchy is as follows:
Which class is it defined in? I'm afraid I can't find it.
Code: Select all
basic_istream->basic_ios->ios_base
-
- Guru
- Posts: 584
- Joined: Thu Jun 19, 2003 3:48 am
- Location: Sanok, Poland
- Contact:
Yes, I find it in the basic_ios.h.
Code: Select all
/**
* @brief The quick-and-easy status check.
*
* This allows you to write constructs such as
* "if (!a_stream) ..." and "while (a_stream) ..."
*/
operator void*() const
{ return this->fail() ? 0 : const_cast<basic_ios*>(this); }
I stay home. Don't call me out.
-
- Guru
- Posts: 584
- Joined: Thu Jun 19, 2003 3:48 am
- Location: Sanok, Poland
- Contact:
-
- New poster
- Posts: 31
- Joined: Sun Feb 25, 2007 6:33 pm
- Location: Tehran
Krzysztof Duleba right there is a converstion operator. for example:
but if you define a conversion operator the code will be correct:
so you can use:
while (cin)
or
while (cin >> n)
for finding this operator see the source code of your compiler (I don't remember which header file). for example in MSDN there is a void * operator and there is no bool operator but if you see the source codes you will find a bool operator
Code: Select all
#include <iostream>
using namespace std;
struct test
{
int a;
};
int main()
{
test a;
while (a) // Syntax error
{
}
return 0;
}
Code: Select all
#include <iostream>
using namespace std;
struct test
{
int a;
operator bool()
{
return true;
}
};
int main()
{
test a;
while (a) // No syntax error
{
}
return 0;
}
while (cin)
or
while (cin >> n)
for finding this operator see the source code of your compiler (I don't remember which header file). for example in MSDN there is a void * operator and there is no bool operator but if you see the source codes you will find a bool operator