Type of std::endl
|
Newbie Member
|
|
| 14Feb2007,04:41 | #1 |
|
My program includes a custom class which uses operator<< similarly to an ostream. I'd like to be able to send it 'endl', but I can't find out what function I need to define to accept it.
|
|
Team Leader
|
![]() |
| 14Feb2007,06:08 | #2 |
|
endl sends a newline followed by a flush of the stream.
|
|
Newbie Member
|
|
| 14Feb2007,06:36 | #3 |
|
Let me rephrase:
I want to be able to have something like: MyClass stream; stream << std::endl; And to do that, I need to define operator<< (MyClass &, _____) What goes in the blank? |
|
Go4Expert Founder
|
![]() |
| 14Feb2007,09:13 | #4 |
|
bloank should be outstream but as far as I remember the first param should be the blank and second one your class
|
|
Team Leader
|
![]() |
| 14Feb2007,18:10 | #5 |
|
Here's a nice tutorial on operator overloading, written by a friend.
|
|
Newbie Member
|
|
| 14Feb2007,18:57 | #6 |
|
Let me rephrase again: I want to create a class "MyStreamLikeClass" which functions similarly to an ostream, so the following code would be legal:
MyStreamLikeClass stream; stream << std::endl; I need to define MyStreamLikeClass &operator<< (MyStreamLikeClass &, _____); where _____ is the appropriate type for endl. shabbir's comment (did he me 'ostream' instead of 'outstream') is not what I want because I am not using the standard C++ streams. The argument which goes first is the stream class, which in my case would be MyStreamLikeClass. |
|
Newbie Member
|
|
| 14Feb2007,19:39 | #7 |
|
Never mind: I managed to work it out by going over headers,
In case anybody else should ever have the same problem: #include <iostream> class MyStream { int total; public: MyStream() : total (0) {} void flush() { std::cout << total << "\n"; total = 0; } MyStream &operator<< (int i) { total = total + i; return *this; } MyStream &operator<< (MyStream &f(MyStream &)) { return f(*this); } ~MyStream() { flush(); } }; MyStream &endl(MyStream &f) { f.flush(); return f; } int main (int argc, char *argv[]) { MyStream str; str << 1 << 2 << 3 << endl << 4 << endl << 7; } |
|
Team Leader
|
![]() |
| 15Feb2007,05:17 | #8 |
|
I would recommend that your version of flush incorporate cout.flush(), otherwise it can be misinterpreted by a user, at it doesn't actually flush the stream, which is the whole point of endl.
|


