Reputation: 219
I have a class Complex and I'm trying to overload the istream operator >> to allow the user to input a complex number in the form "(a, b)". Below is my header file and my implementation. Right now, I'm getting an error saying that my overloaded >> function can not access the real or imaginary data members because they are inaccessible, even though I declared them as friends in the class header file. Can anyone explain what I'm not seeing?
Header file:
// Complex class definition.
#ifndef COMPLEX_H
#define COMPLEX_H
class Complex
{
friend std::ostream &operator<<(std::ostream &, const Complex &);
friend std::istream &operator>>(std::istream &, const Complex &);
public:
explicit Complex( double = 0.0, double = 0.0 ); // constructor
Complex operator+( const Complex & ) const; // addition
Complex operator-( const Complex & ) const; // subtraction
//Complex operator*(const Complex &); // function not implemented yet
private:
double real; // real part
double imaginary; // imaginary part
}; // end class Complex
#endif
Implementation file:
// Complex class member-function definitions.
#include <iostream>
#include <iomanip>
#include "Complex.h" // Complex class definition
using namespace std;
// Constructor
Complex::Complex( double realPart, double imaginaryPart )
: real( realPart ),
imaginary( imaginaryPart )
{
// empty body
} // end Complex constructor
// addition operator
Complex Complex::operator+( const Complex &operand2 ) const
{
return Complex( real + operand2.real,
imaginary + operand2.imaginary );
} // end function operator+
// subtraction operator
Complex Complex::operator-( const Complex &operand2 ) const
{
return Complex( real - operand2.real,
imaginary - operand2.imaginary );
} // end function operator-
// display a Complex object in the form: (a, b)
ostream &operator<<(ostream &out, const Complex &operand2)
{
out << "(" << operand2.real << ", " << operand2.imaginary << ")";
return out; // enable cascading output
}
// change the imaginary and real parts
istream &operator>>(istream &in, Complex &operand2)
{
in.ignore(); // skips '('
in >> setw(1) >> operand2.real; // get real part of the number
in.ignore(2); //ignore the , and space
in >> setw(1) >> operand2.imaginary;
in.ignore(); // skip ')'
return in; // enable cascading input
}
Upvotes: 1
Views: 1615
Reputation: 1
Your error is here
friend std::istream &operator>>(std::istream &, const Complex &);
// ^^^^^
This doesn't match the (correct) signature of your definition
istream &operator>>(istream &in, Complex &operand2)
Upvotes: 5