Oh, and the cin being istream can be overloaded in the same fashion (of course, the class you're overloading for cannot be const in this case, and you must remove any formatting you define in the ostream - I've ignored this removal because it would complicate matters, and I'd probably get it wrong anyway :)
istream& operator>> (istream& s, WriteMe& write)
{
s >> write.m_writethis;
return s;
}
Of course in a real case, you'd have to put all sorts of error checking in there too.
you would use this exactly as you would a built in type:
WriteMe bob;
bob.m_writethis = 77;
cout << bob;
...
WriteMe bill;
cin >> bill; //ignoring the formatting again.
Main Topics
Browse All Topics





by: IainHerePosted on 2001-08-08 at 03:18:28ID: 6363392
Yes, they're overloadable - that's pretty much the reason they were developed. Don't forget that cout is defined as
extern ostream cout;
say you have your own class:
class WriteMe{
public:
double m_writethis;
};
you would overload the << operator to work with cout like this:
ostream& operator<< (ostream&s, const WriteMe& write)
{
return s << "your formatting here " << write.m_writethis;
}
[Ignoring the publicness of the member variable and the uselessness of the class]