Algorithm
Define a class Complex with private members real and imag.
2. Implement a constructor for the Complex class to initialize real and imag.
3. Overload the subtraction operator (-) as a member function inside the Complex class.
3.1 Define the operator function with the signature: Complex operator-(const Complex& other) const.
3.2 Inside the operator function, subtract the real parts and imaginary parts separately.
3.3 Create a new Complex object to store the result of the subtraction.
3.4 Return the newly created Complex object.
4. Define a display function within the Complex class to print the complex number.
5. In the main program:
5.1 Create two Complex objects, num1 and num2, with the desired real and imaginary values.
5.2 Display the original complex numbers.
5.3 Use the overloaded subtraction operator to subtract num2 from num1, storing the result in a new Complex object.
5.4 Display the result of the subtraction.
Code Examples
#1 Code Example- C++ programing Binary Operator Overloading to Subtract Complex Number
Code -
C++ Programming
#include <iostream>
using namespace std;
class Complex
{
private:
float real;
float imag;
public:
Complex(): real(0), imag(0){ }
void input()
{
cout << "Enter real and imaginary parts respectively: ";
cin >> real;
cin >> imag;
}
// Operator overloading
Complex operator - (Complex c2)
{
Complex temp;
temp.real = real - c2.real;
temp.imag = imag - c2.imag;
return temp;
}
void output()
{
if(imag < 0)
cout << "Output Complex number: "<< real << imag << "i";
else
cout << "Output Complex number: " << real << "+" << imag << "i";
}
};
int main()
{
Complex c1, c2, result;
cout<<"Enter first complex number:\n";
c1.input();
cout<<"Enter second complex number:\n";
c2.input();
// In case of operator overloading of binary operators in C++ programming,
// the object on right hand side of operator is always assumed as argument by compiler.
result = c1 - c2;
result.output(>;
return 0;
}
Copy The Code &
Try With Live Editor
Demonstration
C++ Programing Example to Subtract Complex Number Using Operator Overloading-DevsEnv