user2809437
user2809437

Reputation: 492

operator<< and operator >> overloaded functions

in my class definiton i have the following friend functions:

      friend  ostream& operator << (ostream& out, const Person& p1);

      friend istream& operator >> (ostream& out Person& p1);

In my implentation file:

       ostream& operator << (ostream& out, const Person& p1)
      {
       out<< p1.age; //this is a private variable
      }

      istream& operator << (istream& in, Person& p1)
      {
       in >> p1.age; //this is a private variable
      }

But when I compile this, i get an error that says "ostream" does not name a type friend ostream& operator(ostream& out, const Person& p1).. the same thing for istream. Since these are friend functions they can access the private variables i.e age so whats the problem?

Upvotes: 0

Views: 140

Answers (1)

Prettygeek
Prettygeek

Reputation: 2531

So first, your function should return something, so:

ostream& operator << (ostream& out, const Person& p1)
  {
   return out<< p1.age; //this is a private variable
  }

and

istream& operator << (istream& in, Person& p1)
  {
   return in >> p1.age; //this is a private variable
  }

you should remember to add include <iostream> header. and using namespace std;

and most of all one typo

friend istream& operator >> (istream& out Person& p1);

Upvotes: 1

Related Questions