Friend problem (overloading >>/<<)

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?
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.
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.
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.