Exercise:
Write a C++ program to use overloaded operators to subtract complex numbers.
Click Here to View the Solution:
#include <iostream>
using namespace std;
class ComplexSub
{
private:
float R;
float Img;
public:
ComplexSub(): R(0), Img(0){ }
void IN()
{
cout << "Enter the Real and Imaginary values of complex number:\n";
cin >> R;
cin >> Img;
}
// Operator overloading
ComplexSub operator - (ComplexSub cs)
{
ComplexSub TempVar;
TempVar.R = R - cs.R;
TempVar.Img = Img - cs.Img;
return TempVar;
}
void OUT()
{
if(Img < 0)
cout << "Complex number: "<< R << Img << "i";
else
cout << "Complex number: " << R << "+" << Img << "i";
}
};
int main()
{
ComplexSub clx1, clx2, ans;
cout<<"~1st entry~\n";
clx1.IN();
cout<<"~2nd entry~\n";
clx2.IN();
// the object on right hand side of operator is considered as argument by compiler.
ans = clx1 - clx2;
ans.OUT();
return 0;
}
Click Here to View the Output:
~1st entry~ Enter the Real and Imaginary values of complex number: 10 12 ~2nd entry~ Enter the Real and Imaginary values of complex number: 5 8 Complex number: 5+4i
Click Here to View the Explanation:
- There is a separate variable type to handle complex numbers. Hence, three variables of
Complex
type are createdc1x1
,c1x2
, andans
. - User is requested to enter two complex numbers
c1x1
andc1x2
. - Function is created
ans = c1x1 - c1x2
. The operator functionComplexSub Operator - (ComplexSub cs)
is triggered with this. - After the execution of
ans = c1x1 - c1x2
,c1x2
acts an argument for the operator function. This is because wherever binary operators are involved in C++ coding, the variable/object at the right of the operator always acts as an argument. - When the code is executed, the resulting complex number is retuned to the
main ()
function and printed on your screen. - A similar overloading of operators can be done for binary operators, too. These include addition, multiplication, division (
+
,*
,/
, etc).