Hello all,
I am creating a complex number class. Here is the header file 'Complex.h' :
Code:
//February 15, 2006
//Complex class declaration and definition file
class Complex
{
double real, imag;
public:
Complex();
Complex(const Complex&); //Copy constructor (so you can do '=' @ declaration)
Complex(const double&); //Conversion constructor
Complex(const double&, const double&);
Complex conj(const Complex&);
Complex operator+(const Complex&);
Complex operator-(const Complex&);
Complex operator*(const Complex&);
Complex operator/(Complex&);
Complex operator=(const Complex&);
double Re(const Complex&);
double Im(const Complex&);
friend ostream& operator <<(ostream&, Complex&);
friend istream& operator >>(istream&, Complex&);
};
Complex::Complex()
{
real = imag = 0.;
}
Complex::Complex(const Complex &a)
{
real = a.real;
imag = a.imag;
}
Complex::Complex(const double &a)
{
real = a;
imag = 0;
}
Complex::Complex(const double &a, const double &b)
{
real = a;
imag = b;
}
Complex Complex::operator +(const Complex &num)
{
real = real + num.real;
imag = imag + num.imag;
return *this;
}
Complex Complex::operator -(const Complex &num)
{
real = real - num.real;
imag = imag - num.imag;
return *this;
}
Complex Complex::conj(const Complex &another)
{
real = another.real;
imag = -another.imag;
return *this;
}
Complex Complex::operator *(const Complex &num)
{
double a = real, b = imag, c = Re(num), d = Im(num);
real = a*c - b*d;
imag = a*d + b*c;
return *this;
}
Complex Complex::operator /(Complex &den)
{
Complex den_star = conj(den);
double new_den = Re(den_star * den);
*this = *this * den_star;
real = real / new_den;
imag = imag / new_den;
return *this;
}
Complex Complex::operator =(const Complex &another)
{
real = another.real;
imag = another.imag;
return *this;
}
double Complex::Re(const Complex &a)
{
return a.real;
}
double Complex::Im(const Complex &a)
{
return a.imag;
}
Here is the main cpp file:
Code:
#include <iostream.h>
#include "Complex.h"
ostream& operator <<(ostream &out, Complex &a)
{
if(a.real != 0)
out<<a.real;
if(a.imag < 0)
out<<" - j"<<-a.imag;
if(a.imag > 0)
out<<" + j"<<a.imag;
if(a.real == 0 && a.imag == 0)
out<<"0";
return out;
}
istream& operator >>(istream &in, Complex &a)
{
in>>a.real>>a.imag;
return in;
}
int main()
{
Complex a(3,5);
cout<<a<<endl;
Complex b(-1,-2);
cout<<b<<endl;
cout<<"----------------------"<<endl;
cout<<conj(a)<<endl;
return 0;
}
For some reason, I am getting an "undeclared identifier" error in the main program when I call the conj(a) function, but it is clearly defined in the main program (and it is a very simple function). Maybe the answer is right in front of me, but I've been looking at it so much that I just don't see anything anymore. Thanks for all your help.
Best,
Bill83