It depends on how you overload it for you class.
- In case of
std::cout
,<<
is used to write to standard output.>>
is not overloaded forstd::cout
. Sostd::cout >> x
would give compilation error. - In case of
std::cin
,>>
is used to read from standard input.<<
is not overloaded forstd::cin
. Sostd::cin << x
would give compilation error. - For your custom class, you can overload
<<
or>>
, or both, and in the function you can do anything you like. For example, in the following code, I overload<<
forstd::vector<T>
to add elements to vector,template<typename T> std::vector<T> & operator<<(std::vector<T> & v, T const & item) { v.push_back(item); return v; }
Now I can use this overload to write this:std::vector<int> v; v << 1 << 2 << 3 << 4 << 5; //inserts all integers to the vector!
All the integers are added to the vector! See online demo : http://ideone.com/TsqtSSimilarly, we can overload>>
forstd::vector<T>
to print all the items in it as:template<typename T> std::vector<T> & operator>>(std::vector<T> & v, std::ostream & out) { for(size_t i = 0 ; i < v.size(); i++ ) std::cout << v[i] << std::endl; return v; }
And now we can print the vector as:v >> std::cout; //crazy!
Online demo : http://ideone.com/BVSm7
The point is that you can overload these operators in whatever way you want. How crazy or sane the overload and their usage would look is up to you. For example, the syntax v >> std::cout
would look crazy to most programmers, as I guess. A better and probably sane overload would be for std::ostream
as:
template<typename T> std::ostream & operator << (std::ostream & out, const std::vector<T> & v) { for(size_t i = 0 ; i < v.size(); i++ ) out << v[i] << std::endl; return out; }
Now you can write this:
std::cout << v << std::endl; //looks sane!
Demo : http://ideone.com/jce2R