[LC++]Overlading << to input into my class

Carlo Wood carlo at alinoe.com
Wed Nov 28 12:58:12 UTC 2001


On Tue, Nov 27, 2001 at 07:43:19PM -0500, David Filion wrote:
> First some info.  Here is an outline of the class I'm creating...
> 
> class Log {
> private:
> 	ofstream outfile;
> 	// Other members..
> public:
> 	// Constructors, destructors here
> 	// Other methods here..
> };
> 
> I would like to overload the << operator so I can do the following:
> mylog << "so text";
> 
> For example:
> 
> main ()
> {.
> 	Log mylog ("somename");
> 	// ... Do some other stuff ...
> 
> 	mylog << "message to be sent to outfile member of mylog" << endl;
> }
> 
> 
> All the references on overloading << I've come accrss refer to setting up
> << as a friend 
> so I can output my class to cout.  I want to output the provided text to
> the outfile member of
> the Log class along with some other info.
> 
> Thanks.

If this is for debugging output, then why don't you use libcwd?
See http://libcw.sourceforge.net/debugging/

What you want is not possible the way you are trying to do it.
Of course, you could overload operator<< this way:

Log& operator<<(Log& log, char const* s)
{
  log.outfile << s;
  return log;
}

But that is a VERY bad idea.  And believe me, I am an expert in this field ;).
The whole class 'ostream' exists purely for overloading purpose in combination
with operator<<, you really don't want to use operator<< with other classes.

It has taken me many _years_ to develop libcwd and I believe this is not
trivial stuff.  Your best bet is to start using libcwd imho (the library
comes with an example to direct the debugging output to syslog, but it
should be relatively easy to write to anything else).

-- 
Carlo Wood <carlo at alinoe.com>

PS The reason that it is a bad idea is that classes only define
   an operator<<(ostream&, ...).  Using anything else for your log file
   would be 100% NON-object-oriented and forcing you to define a
   new operator<<(Log&, ...) for every object you want to use it with
   in the future.




More information about the tuxCPProgramming mailing list