Solved

How to overload <<

Posted on 1999-01-04
4
199 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 100 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

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Errors will happen. It is a fact of life for the programmer. How and when errors are detected have a great impact on quality and cost of a product. It is better to detect errors at compile time, when possible and practical. Errors that make their wa…
  Included as part of the C++ Standard Template Library (STL) is a collection of generic containers. Each of these containers serves a different purpose and has different pros and cons. It is often difficult to decide which container to use and …
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

679 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