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.
#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.
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.
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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
mithander i do not think friends area affected by public and private