Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations MikeeOK on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Overloading << & >> Operators 1

Status
Not open for further replies.

DavidTheLazyStudent

Technical User
Mar 24, 2003
3
US
Each time I try to add overloaded input/output I get a compiler message about accessing the class's private data. If I REM out the statments it functions as expected.

My Friend statment is:
friend ostream& operator << (ostream &out, Meal &aMeal);

With Meal being the Class, aMeal is representing an Object of the Class. I believe this is my problem but can not find any solutions in my books. Is aMeal suspose to be only the object name and not just anything I use for refferencing inside my function?

*ostream& operator << (ostream &out, Meal &aMeal)
{
out << aMeal.entree << '\t' << aMeal.calorie << '\n';
return(out);
}
I have the exact same problem on the input.
 
Define the object reference as const and also dont change the return value in the definition signature

Code:
class Meal{
... other stuff
  friend ostream& operator <<( ostream& os, const Meal& oMeal);
};

// then in implementation file
ostream& operator <<( ostream& os, const Meal& oMeal){
  os << oMeal.calorie << endl;
  return os;
}

hope that helps
-pete
 
Be attentive on symbols, look at * Ion Filipski
1c.bmp


filipski@excite.com
 
FYI
I had a similar problem that was fixed if I used

<iostream.h>

instead of

<iostream>
using namespace std;

I then checked MSDN to find out that the problem was fixed with a VS srvPack. If you choose to battle wits with the witless be prepared to lose.

[cheers]
 
Thank You all... that was it foada. I did and it compiled fine. This has been driving me crazy.

(The * was a result of a careless /* not really in my program).
 
Wait a second... you got it to work with the code you posted? That's just not right!

you have the return type declared as ostream& and the definition declared as *ostream&

If that works there is a huge bug in the compiler!

-pete
 
No, that was a typo posting. The * was not in my program. I REM'ed it out to test that it would compile without those statements to isolate my problem. I had also made it a const as you had pointed out. But it still didn't compile, untill I used <iostream.h> instead of just plain <iostream> and using namespace std;

It works great, again thanks all.



Now if I could just do something about my short fat fingers.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top