Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

How to overload <<

Posted on 1999-01-04
4
Medium Priority
?
204 Views
Last Modified: 2010-08-05
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.
0
Comment
Question by:girishr
4 Comments
 
LVL 8

Expert Comment

by:Answers2000
ID: 1181492
Don't you mean ostream& instead of all those iostream&'s ?
0
 

Expert Comment

by:Mithander
ID: 1181493
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.
0
 

Accepted Solution

by:
koskia earned 300 total points
ID: 1181494
Answer2000 is right,
you should use ostream and not iostream
this should solve the problem.
the cout object recieves ostreams, which is driven from iostream, ofcourse it can't make the downcast
0
 

Author Comment

by:girishr
ID: 1181495
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
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Unlike C#, C++ doesn't have native support for sealing classes (so they cannot be sub-classed). At the cost of a virtual base class pointer it is possible to implement a pseudo sealing mechanism The trick is to virtually inherit from a base class…
Written by John Humphreys C++ Threading and the POSIX Library This article will cover the basic information that you need to know in order to make use of the POSIX threading library available for C and C++ on UNIX and most Linux systems.   [s…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
Suggested Courses

972 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question