Link to home
Start Free TrialLog in
Avatar of girishr
girishr

asked on

How to overload <<

Say is there anything wrong in this code.i want to overload <<.

#include <iostream.h>

class Boy
{
 friend iostream& operator << (iostream&,Boy &);
 public:Boy(int a) {age=a;}
 private:int age;
};

iostream& operator << (iostream& ios,Boy &b)
{
 ios << b.age;
 return ios;
}
main()
{
 Boy b(1);
 cout << b;
}


I want the age of the boy to be printed whenever i give cout<<b ...but the compiler gives an error (illegal structure format for cout << b)

Please help immediately.
Avatar of Answers2000
Answers2000

Don't you mean ostream& instead of all those iostream&'s ?
Classes default to Private.  There for the:
friend iostream& operator << (iostream&,Boy &);
would be private.  I am not sure if this matters because it is not a member function.  Just a thought though.
ASKER CERTIFIED SOLUTION
Avatar of koskia
koskia

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of girishr

ASKER

Thanks.I knew it all the time and i still made a mistake..
mithander i do not think friends area affected by public and private