I have a question about overloading operator<< . Actually I am trying to understand how it works when chaining multiple calls to this operator. I have a very simple class (MyOut) with an overloaded operator<<, which takes a string as input parameter and returns a reference to an ostream object (std::cout in this case).
In the main file I instantiate an object of MyOut and then write a message to console in two different ways:
1. chaining several strings
2. sending individually each string
What I don't understand is why in the first case (when chaining) the overloaded operator is called only one time, for the first string? What happens for the other two strings ?!? How actually the chaining works ?
What I am trying to do is to buffer the input string "str", doing something like that:
m_str += str; (instead of the printf call)
where m_str is std::string as well and is cleared somewhere else. Which works fine only when not chaining strings.
I would very much appreciate if you have any answer to my problem.
Cheers,
buburuz
Expand|Select|Wrap|Line Numbers
- #include <iostream>
- #include <fstream>
- using namespace std;
- class MyOut {
- ostream& output;
- public:
- MyOut()
- : output( std::cout ) {}
- ~MyOut() {}
- std::ostream& operator<<(const std::string& str)
- {
- printf ("+++ called operator<<\n");
- return output << str;
- }
- };
- int main ()
- {
- MyOut p;
- // chaining
- p << "This is " << "just a " << "test!\n" << std::endl;
- // individual calls
- p << "This is ";
- p << "just a ";
- p << "test!" << std::endl;
- return 0;
- }