operator overloading problem

Hi everyone.
I'm trying to create a simple c++ program to do complex number calculation.
the basic form is (a + bi) ... (c + di)
the ... part can be filled with +, -, * , or /
i've made the addition, substraction , and multiplication part using operator overloading..
when i tested out the addition, it work properly..
but when i tried the substraction and multiplication, it gave me the same result as addition.
anyone know why? thanks

here is the code for addition part :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
complexNo complexNo::operator+ (const complexNo& complex)const
{
	complexNo temp;
	temp.real = real + complex.real;
	temp.imaginary = imaginary + complex.imaginary;
	
	return temp;
	
	// (a + bi) + (c + di)
	//=(a + c) + (b + d)i
	//	a = real
	//	b = imaginary
	//	c = complex.real
	//	d = complex.imaginary
}



and here is there code for substraction part :
i just changed all '+' into '-'.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
complexNo complexNo::operator- (const complexNo& complex)const
{
	complexNo temp;
	temp.real = real - complex.real;
	temp.imaginary = imaginary - complex.imaginary;
	
	return temp;
	
	//(a + bi) - (c + di)
	//=(a - c) + (b - d)i
	//	a = real
	//	b = imaginary
	//	c = complex.real
	//	d = complex.imaginary
}


here is the multiplication part :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
complexNo complexNo::operator* (const complexNo& complex)const
{
	complexNo temp;
	temp.real = ((real*complex.real) - (imaginary*complex.imaginary));
	temp.imaginary = ((real*complex.imaginary) +(imaginary*complex.real));
	
	return temp;

	//(a + bi) * (c + di)
	//=(ac - bd) + (ad + bc)i
	//	a = real
	//	b = imaginary
	//	c = complex.real
	//	d = complex.imaginary 


and in the main function, i just declare a simple code like this :

1
2
3
	complexNo complex1 (0, 0);	//first complex number
	complexNo complex2 (0, 0);	//second complex number
	complexNo complex3 (0, 0);	//third complex number 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
	if (operation == '+')
	{
		complex3 = complex1 + complex2;
		complex3.print();
	}
	else if (operation == '-')
	{
		complex3 = complex1 - complex2;
		complex3.print();
	}
	else if (operation == '*')
	{
		complex3 = complex1 * complex2;
		complex3.print();
	}
	}


this is not a full code.
i just copy those part where i think is related to the problem.

hope you guys can help. thanks.
Would you mind if you copy past the hole code?
If your constructor is overloaded i would suggest this type syntax

complexNo complexNo::operator* (const complexNo& complex)const
{


return complexNo(((real*complex.real) - (imaginary*complex.imaginary)) ,((real*complex.imaginary) +(imaginary*complex.real)));

}


The only difference is you don't create a temp object ..Can you please sent the hole code :)
Last edited on
Topic archived. No new replies allowed.