Reputation: 601
I'm trying to overload the >> and << operators for use in a complex number class. For some reason my << and >> functions cannot access the real and imaginary parts of the complex objects even though I've made them friends of the class.
Complex.h:
#ifndef COMPLEX_H
#define COMPLEX_H
class Complex
{
friend std::ostream &operator<<(std::ostream &out, const Complex &c);
friend std::istream &operator>>(std::istream &, Complex &);
public:
explicit Complex(double = 0.0, double = 0.0); // constructor
Complex operator+(const Complex &) const;
Complex operator-(const Complex &) const;
#endif
Complex.cpp:
#include "stdafx.h"
#include "Complex.h"
#include <iostream>
using namespace std;
istream &operator>>(istream &input, Complex &complex) // input
{
cout << "enter real part:\n";
input >> complex.real;
cout << "enter imag part: \n";
input >> complex.imaginary;
return input;
}
std::ostream &operator<<(std::ostream &out, Complex c) //output
{
out<<"real part: "<<c.real<<"\n";
out<<"imag part: "<<c.imag<<"\n";
return out;
}
Upvotes: 0
Views: 2639
Reputation: 66981
You didn't friend the same function you defined. You friended the first, and defined the second:
friend std::ostream &operator<<(std::ostream &out, const Complex &c);
std::ostream &operator<<(std::ostream &out, Complex c)
Also, Is the member named imaginary
or imag
?
input >> complex.imaginary;
out<<"imag part: "<<c.imag<<"\n";
Upvotes: 2