TIP: Click on subject to list as thread! ANSI
echo: c_plusplus
to: BRIAN S
from: JERRY COFFIN
date: 1997-10-29 00:28:00
subject: write

On (27 Oct 97) Brian S wrote to All...
 BS> I was trying to make a class that worked similar to the cout class,
 BS> just for some practice and I was wondering if anyone could help.  This
 BS> is what I have done so far :
 BS> -------------------------------------------------------------
 BS> #include 
 BS> class myoutput {
 BS>   public:
 BS>     void operator<< (char* s)
 BS>       {
 BS>         cout << s;
 BS>       }
 BS> };
 BS> void main ()
 BS> {
 BS>   myoutput write;
 BS>   write << "Hello World";
 BS> }
 BS> -------------------------------------------------------------------
 BS>
 BS> I would like to be able to call my << function multiple times like the
 BS> cout class.  for example :
 BS> write << "Hello " << "World";
To allow this, it helps to take a look at what a single write really
translates as:
    write.operator<<("Hello World");
Now, when you try to string operators together, you end up nesting
function calls, something like this:
    (write.operator<<("Hello ")).operator<<("World");
For this to work, each << operator function has to return an object for
which the << operator has been overloaded -- specifically, the stream on
which it's operating:
class myoutput {
public:
    myoutput &operator<<(char const *string) {
        cout << string;
        return *this;
    }
};
When you use this, you basically invoke the function once on the
object specified in the original statemente (`write' in your example).
This function then returns a reference to the same object, which is then
used to invoke the output function again to write the second string.
Since each invocation allows another, we can string as many together
this was a we want to.
    Later,
    Jerry.
--- PPoint 2.02
---------------
* Origin: Point Pointedly Pointless (1:128/166.5)

SOURCE: echomail via exec-pc

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.