Sign in to follow this  
redirectionkid

cout/cin and bitwise shifting

Recommended Posts

redirectionkid    152
Just out of curiosity, is the "<<" operator that is used in conjunction with the cout/cin statements the same as a bitwise shift? Or does the compiler have some way of differentiating between the two based upon the context with which they are being applied? I haven't really found any solid tutorials or references that discuss the fundamentals behind cout/cin... mostly just "hello world" junk. -Thanks

Share this post


Link to post
Share on other sites
Sneftel    1788
It's the same operator. The stream classes have the << and >> operators overloaded to do something completely different from bit-shifting.

Share this post


Link to post
Share on other sites
Roboguy    794
std::ostream (which cout is an instance of) overloads the << operator and std::istream (which cin is an instance of) overloads the >> operator. You probably want to look for a tutorial on operator overloading.

Share this post


Link to post
Share on other sites
redirectionkid    152
Quote:
Original post by Roboguy
std::ostream (which cout is an instance of) overloads the << operator and std::istream (which cin is an instance of) overloads the >> operator. You probably want to look for a tutorial on operator overloading.


I was thinking the same thing... about the operator overloading tutorial, ofcourse. :P

Share this post


Link to post
Share on other sites
Fruny    1658
Quote:
Original post by redirectionkid
Just out of curiosity, is the "<<" operator that is used in conjunction with the cout/cin statements the same as a bitwise shift? Or does the compiler have some way of differentiating between the two based upon the context with which they are being applied?


When you write a << b, it is equivalent to operator<<(a,b);.

std::cin is a global variable of type std::istream (input stream).
std::cout is a global variable of type std::ostream (output stream).

The compiler differentiates based on the type of the parameters on the left and right of the operator. That's "operator overloading".

You can do it yourself, with your own types. For example, you could do:

struct foo;
{
int i,j,k;
};

std::istream& operator>>(std::istream& is, foo& f)
{
return is >> f.i >> f.j >> f.k;
}

std::ostream& operator<<(std::ostream& os, const foo& f)
{
return os << f.i << ' ' << f.j << ' ' << f.k;
}

Now, this enables you to write code like:

foo f;
std::cin >> f;
std::cout << f;

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this