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

2
  • Please don't design your class in this way. It will be so confusing. Commented Jul 10, 2013 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. Commented Jul 10, 2013 at 16:43

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.