TIP: Click on subject to list as thread! ANSI
echo: c_plusplus
to: JAMIE KOWINSKY
from: JERRY COFFIN
date: 1997-09-17 22:14:00
subject: cout`ing an object

On (16 Sep 97) Jamie Kowinsky wrote to All...
 JK> Have a question for all you C++ pros out there.
 JK> say I have a class defined, lets call it class test, this class has a
 JK> number of private variables and public functions.  It includes a
 JK> function to
 JK> print out some private data fileds ex "void test:print(void)" this
 JK> function simply does "cout << stuff" on a number of things, in effect
 JK> printing the fields of the object.
 JK> Now say i have some object created with this class ex:
 JK> test thing = test(....);
 JK> normally to print this thing i have to call "thing.print" I would
 JK> rather do a "cout << thing".  I am fimular with overloading operators,
 JK> and I would like to know if its possible to overload the << operator
 JK> somehow to do this. Or perhaps there is another way.
Just create a global overload of operator<< to do what you want,
something like:
class test {
    int stuff;
public:
    void print(ostream &str) {
        str << stuff;
    }
    void print() {
        printf(cout);
    }
};
ostream &operator<<(ostream &str, test const &t) {
    return t.print(str);
}
    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™.