Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/forums/cpp/)
-   -   Type of std::endl (http://www.go4expert.com/forums/type-of-stdendl-t2998/)

ralphmerridew 14Feb2007 04:41

Type of std::endl
 
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.

DaWei 14Feb2007 06:08

Re: Type of std::endl
 
endl sends a newline followed by a flush of the stream.

ralphmerridew 14Feb2007 06:36

Re: Type of std::endl
 
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?

shabbir 14Feb2007 09:13

Re: Type of std::endl
 
bloank should be outstream but as far as I remember the first param should be the blank and second one your class

DaWei 14Feb2007 18:10

Re: Type of std::endl
 
Here's a nice tutorial on operator overloading, written by a friend.

ralphmerridew 14Feb2007 18:57

Re: Type of std::endl
 
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.

ralphmerridew 14Feb2007 19:39

Re: Type of std::endl
 
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;
}

DaWei 15Feb2007 05:17

Re: Type of std::endl
 
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.


All times are GMT +5.5. The time now is 03:54.