0

Please do read before flagging as a duplicate

I am overloading operators >> and << for reading complex numbers with real part r and imaginary part i;

#include<iostream.h>
#include<conio.h>
#include<stdio.h>
class complex
{
    int r,i;
public:
complex()
{ i=r=0;}
friend istream& operator>>(istream&, complex&);
friend ostream& operator<<(ostream&,complex&);
};
istream& operator>>(ifstream &din, complex &x)
{
    din>>x.r;
    din>>x.i;
    return din;
}
ostream& operator<<(ostream &dout, complex &x)
{
dout<<x.r<<x.i;
return dout;
}
void main()
{
clrscr();
complex x;
cin>>x;
cout<<x;

}

The error is that r and i are not accessible at code part

din>>x.r; din>>x.i;

The error is that r and i are private so not accessible Aren't normal friend functions able to access private variables. Why does it fail for >> only?

Note: << operator works fine. only >> fails

Xperiaz X
  • 216
  • 1
  • 6
  • 16
  • Please don't design your class in this way. It will be so confusing. – Bathsheba Jul 10 '13 at 15:08
  • `iostream.h` is not a standard header. Use `iostream`. None of the standard C++ headers have extensions. `void main` is also not a legal signature. Use `int main`. – chris Jul 10 '13 at 16:43

1 Answers1

6

The friend declaration of operator>> takes an istream argument, but the implementation takes an ifstream argument, making it a completely different (and thus non-friend) function. Remove the extra f, and it should work.

legoscia
  • 39,593
  • 22
  • 116
  • 167