Complex Numbers
Mar 11, 2010 at 5:35pm UTC
Hello Everyone!
I am currently working on a program that adds, subtracts, and multiplies complex numbers. However, I am currently getting some very weird errors and I don't know how to fix them. If someone could help me with that, it would be great.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
Here is what I have so far:
#include <iostream>
using namespace std;
class Complex {
public :
double realPart;
double imaginaryPart;
Complex();
Complex(double realPart, double imaginaryPart);
Complex operator +(const Complex &right);
Complex operator -(const Complex &right);
Complex operator *(const Complex &right);
void PrintComplex();
};
Complex Complex::operator +(const Complex &right)
{
Complex temp;
temp.realPart = realPart + right.realPart;
temp.imaginaryPart = imaginaryPart + right.imaginaryPart;
return temp;
}
Complex Complex::operator -(const Complex &right)
{
Complex temp;
temp.realPart = realPart - right.realPart;
temp.imaginaryPart = imaginaryPart - right.imaginaryPart;
return temp;
}
Complex Complex::operator *(const Complex &right)
{
Complex temp;
temp.realPart = realPart*right.realPart;
temp.imaginaryPart = imaginaryPart*right.imaginaryPart;
return temp;
}
void Complex::PrintComplex()
{
cout << realPart << " + " << imaginaryPart << "i" << endl;
}
int main()
{
Complex a(3.5, 2.5);
Complex b(4.5, 9.6);
Complex c, d, e;
c = a + b;
d = a - b;
e = a*b;
}
Mar 11, 2010 at 5:58pm UTC
This is beause you did not define your constructor. Yes you did declare it, but the linker will look for the definition and will end up crying for not finding one. Just use something like this: (be sure to change both constructor declarations!)
1 2 3 4 5
Complex (double r, double i)
{
realPart = r;
imaginaryPart = i;
}
Second point is more of a mathematical one. Multiplication of complex numbers is the following:
(a + bi) * (c + di) = (ac - bd) + (ad + bc) i
Greatings, Maikel
EDIT: did some changes
Last edited on Mar 11, 2010 at 6:00pm UTC
Mar 11, 2010 at 6:36pm UTC
ok thanks for the help...if I have any other problems I will post it here...
Topic archived. No new replies allowed.