--> Jamie Kowinsky wrote to All <--
JK>say I have a class defined, lets call it class test, this class has
JK>a number of private variables and public functions. It includes a
JK>function to print out some private data fileds ex "void
JK>test:print(void)" this function simply does "cout << stuff" on a
JK>number of things, in effect printing the fields of the object.
JK>
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
JK>operators, and I would like to know if its possible to overload the
JK><< operator somehow to do this. Or perhaps there is another way.
You bet, overloading << is an important C++ ability.
// I did not test this code, but it should be close...
#include
class test {
private: // Aside: yes, Neil, I explicitly do this!
int a;
const char *s;
public:
// Constructor with default arguments
test(int i = 1, const char *str = "No String") : a(i), s(str) { }
// This is how to overload <<
friend ostream & operator << (ostream & os, test & t)
{
os << "The int is " << t.a << endl;
os << "The string is " << t.s << endl;
return os;
}
};
int main(void)
{
test t1();
test t2(0, "Overloaded <<");
cout << t1 << endl;
cout << t2 << endl;
return 0;
}
Cliff Rhodes
cliff.rhodes@juge.com
crhodes@flash.net
X CMPQwk 1.42 1692 X"If you would live innocently, seek solitude." - P
--- Maximus/2 3.01
---------------
* Origin: COMM Port OS/2 juge.com 204.89.247.1 (281) 980-9671 (1:106/2000)
|