Solved

How to overload <<

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

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

747 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now