I'm implementing istream and ostream overloading for a program that takes in 3 objects, adds them, subtracts them, and multiplies them. I'm having difficulty in outputting the objects. The program outputs the first object just fine, but for some reason defaults the other two...and I've looked through the program and can't figure out what I'm doing wrong. Here's my code:
Code:
#ifndef COMPLEX_H
#define COMPLEX_H
#include <string>
class Complex
{
friend std::ostream &operator<<(std::ostream &, const Complex &);
friend std::istream &operator>>(std::istream &, Complex &);
public:
explicit Complex(double = 0.0, double = 0.0);
Complex operator+(const Complex &) const; //addition
Complex operator-(const Complex &) const; //subtration
Complex operator*(const Complex &) const; // mult
bool operator !=(const double &);
bool operator ==(const double &);
private:
double real;
double imag;
};
#endif
Code:
#include <iostream>
#include "complex.h"
#include <string>
using namespace std;
//constructor
Complex::Complex(double realPart, double imaginaryPart)
: real(realPart),
imag(imaginaryPart)
{
}
Complex Complex::operator+(const Complex &operand2) const
{
return Complex(real + operand2.real, imag + operand2.imag);
}
Complex Complex::operator-(const Complex &operand2) const
{
return Complex(real - operand2.real, imag - operand2.imag);
}
Complex Complex::operator*(const Complex &operand2) const
{
return Complex(real * operand2.real, imag * operand2.imag);
}
ostream &operator<<(ostream &output, const Complex &d)
{
cout << "(" << d.real << "," << d.imag << ")" << "\n";
return output;
}
istream &operator>>(istream &input, Complex &d)
{
input.ignore(); //ignore (
input >> d.real;
input.ignore(); //comma
input >> d.imag;
input.ignore(); //)
return input;
}
Code:
#include <iostream>
#include "complex.h"
using namespace std;
int main()
{
Complex x;
cout << "Please enter x object in the form (1.2, 3.4)" << endl;
cin >> x;
Complex y;
cout << "Please enter y object in the form (1.2,3.4)" << endl;
cin >> y;
Complex z;
cout << "Please enter z object in the form (1.2,3.4) " << endl;
cin >> z;
cout << "The objects were:" << endl;
cout << x << "\n" << endl;
cout << y << "\n" << endl;
cout << z << "\n" << endl;
}