hello again,
I've run into a problem in overloading << and >>. Within the definition when compiling its saying that 'real' and 'imaginary' are undeclared, these errors are in lines 45(real), 46(imaginary) and 57(both). Whats wrong here? And if you could please let me know how to correct this.
Heres the header file.
#include <iostream>
using namespace std;
class Complex
{
public:
Complex();
Complex(double real, double imaginary);
Complex(double real);
const Complex operator +(const Complex& value) const;
const Complex operator -(const Complex& value) const;
const Complex operator -() const;
const Complex operator *(const Complex& value) const;
friend ostream& operator <<(ostream& outputStream, const Complex value);
friend istream& operator >>(istream& inputStream, Complex value);
private:
double real;
double imaginary;
};
Here is the .cpp file the errors are actually in.
#include <iostream>
#include <math.h>
#include <cstdlib>
using namespace std;
#include "Complex.h"
Complex::Complex(): real(0), imaginary(0)
{ }
Complex::Complex(double realPart, double imaginaryPart): real(realPart), imaginary(imaginaryPart)
{ }
Complex::Complex(double realPart): real(realPart), imaginary(0)
{ }
const Complex Complex::operator +(const Complex& secondValue) const
{
double realSum, imaginarySum;
realSum = real + secondValue.real;
imaginarySum = imaginary + secondValue.imaginary;
return Complex(realSum, imaginarySum);
}
const Complex Complex::operator -(const Complex& secondValue) const
{
double realDiff, imaginaryDiff;
realDiff = real - secondValue.real;
imaginaryDiff = imaginary - secondValue.imaginary;
return Complex(realDiff, imaginaryDiff);
}
const Complex Complex::operator -() const
{
return Complex(-real, -imaginary);
}
// just a reminder that complex multiplication is defined as:
// (a+bi)(c+di) = (ac-bd) + (ad-bc)i.
// [url]http://mathworld.wolfram.com/ComplexMultiplication.html[/url]
const Complex Complex::operator *(const Complex& secondValue) const
{
double realProduct, imaginaryProduct;
realProduct = real*secondValue.real-imaginary*secondValue.imaginary;
imaginaryProduct = real*secondValue.imaginary-imaginary*secondValue.real;
return Complex(realProduct, imaginaryProduct);
}
ostream& operator <<(ostream& outputStream, const Complex& value)
{
outputStream << real;
if (imaginary < 0)
outputStream << "-";
else
outputStream << "+";
outputStream << imaginary << "i";
return outputStream;
}
istream& operator >>(istream& inputStream, const Complex& value)
{
char sign, i;
inputStream >> real >> sign >> imaginary >> i;
if (sign == '-')
imaginary = -imaginary;
return inputStream;
}
Thank you in advance.