Overloading >> and <<

From: job (noway_at_jose.com)
Date: 01/31/04


Date: Sat, 31 Jan 2004 02:42:40 GMT

I'm working thru Lafore's Object Oriented Programming in C++ book and in
Chap 12 he has an example where he tries to overload << and >> ....

// englio.cpp
// overloaded << and >> operators
#include <iostream>
using namespace std;
////////////////////////////////////////////////////////////////
class Distance //English Distance class
   {
   private:
      int feet;
      float inches;
   public:
      Distance() : feet(0), inches(0.0) //constructor (no args)
         { }
                                         //constructor (two args)
      Distance(int ft, float in) : feet(ft), inches(in)
         { }
      friend istream& operator >> (istream& s, Distance& d);
      friend ostream& operator << (ostream& s, Distance& d);
   };
//--------------------------------------------------------------
istream& operator >> (istream& s, Distance& d) //get Distance
   { //from user
   cout << "\nEnter feet: "; s >> d.feet; //using
   cout << "Enter inches: "; s >> d.inches; //overloaded
   return s; //>> operator
   }
//--------------------------------------------------------------
ostream& operator << (ostream& s, Distance& d) //display
   { //Distance
   s << d.feet << "\'-" << d.inches << '\"'; //using
   return s; //overloaded
   } //<< operator
////////////////////////////////////////////////////////////////
int main()
   {
   Distance dist1, dist2; //define Distances
   Distance dist3(11, 6.25); //define, initialize dist3

   cout << "\nEnter two Distance values:";
   cin >> dist1 >> dist2; //get values from user
                                   //display distances
   cout << "\ndist1 = " << dist1 << "\ndist2 = " << dist2;
   cout << "\ndist3 = " << dist3 << endl;
   return 0;
   }

The above was downloaded from his website, when I try and compile I get
--------------------Configuration: test - Win32 Debug--------------------
Compiling...
test.cpp
C:\Documents and Settings\Administrator\My Documents\Programming\O O Prog in
C++\Chap14\test\test.cpp(23) : error C2248: 'feet' : cannot access private
member declared in class 'Distance'

I thought the friend keyword allowed access to private members ? I tried
other examples from other books with the same results for overloading stream
operators.

I've overloaded other operators with success, but can't get << and >> to
work is there something I'm missing ??



Relevant Pages