Friend problem (overloading >>/<<)
Oct 3, 2010 at 7:59am UTC
Hiya. Trying to overload the stream insertion/extraction operators, but apparently my friend functions aren't being recognized.
It's about rectangles. Here's the header.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#ifndef rectangle_h
#define rectangle_h
#include <iostream>
using namespace std;
class rectangleType {
friend ostream& operator <<(ostream&, const rectangleType&);
friend istream& operator >>(istream&, rectangleType&);
public :
//Standard rectangle stuff. Area, perimeter, and so on. I could supply code for these if needed.
private :
double length;
double width;
};
#endif
Member definitions for rectangle.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
#include "rectangle.h"
using namespace std;
ostream& operator <<(ostream osObject, const rectangleType& rectangle)
{
osObject << "Length = " << rectangle.length
<< "Width = " << rectangle.width;
return osObject;
}
istream& operator >>(istream isObject, rectangleType& rectangle)
{
isObject >> rectangle.length >> rectangle.width;
return isObject;
}
This is an error since width and length are private. But I thought friend functions had access to the private members of that class.
So! Can anybody tell me what I'm doing wrong with this code?
Oct 3, 2010 at 8:27am UTC
You declared the functions differently from the friend declarations. Instead of:
1 2
ostream& operator <<(ostream osObject, const rectangleType& rectangle)
istream& operator >>(istream isObject, rectangleType& rectangle)
You need:
1 2 3
//note that the streams are references
ostream& operator <<(ostream& osObject, const rectangleType& rectangle)
istream& operator >>(istream& isObject, rectangleType& rectangle)
Your friend declaration said that they were references, but your functions passed the object.
Oct 3, 2010 at 8:30am UTC
Your delcaration and implementation do not agree.
In your declaration, istream and ostream are passed by reference.
1 2
friend ostream& operator <<(ostream& , const rectangleType&);
friend istream& operator >>(istream& , rectangleType&);
In your implementation, istream and ostream are passed by value.
1 2
ostream& operator <<(ostream osObject, const rectangleType& rectangle)
istream& operator >>(istream isObject, rectangleType& rectangle)
To the compiler, these are different functions. Therefore, the by-value functions are not recognized as friends.
Oct 3, 2010 at 8:38am UTC
Kind of an embarrassing error, but I pretty much had to post it. Not sure I'd have spotted it. Thanks!
Topic archived. No new replies allowed.