Google News
logo
C++ Program to Subtract Complex Number Using Operator Overloading
In the following example of C++ program that demonstrates how to subtract complex numbers using operator overloading :
Program :
#include <iostream>

class Complex {
private:
    double real;
    double imag;

public:
    Complex(double real, double imag) : real(real), imag(imag) {}

    Complex operator-(const Complex& other) const {
        double newReal = real - other.real;
        double newImag = imag - other.imag;
        return Complex(newReal, newImag);
    }

    void print() const {
        std::cout << real << " + " << imag << "i" << std::endl;
    }
};

int main() {
    Complex x(5, 3);
    Complex y(2, 1);

    Complex z = x - y;

    std::cout << "x = ";
    x.print();

    std::cout << "y = ";
    y.print();

    std::cout << "z = x - y = ";
    z.print();

    return 0;
}
Output :
x = 5 + 3i
y = 2 + 1i
z = x - y = 3 + 2i
In this example, we define a Complex class with a real and imaginary component. We overload the subtraction operator (-) using the following member function :
Complex operator-(const Complex& other) const {
    double newReal = real - other.real;
    double newImag = imag - other.imag;
    return Complex(newReal, newImag);
}
​

This function takes another Complex object as its argument, subtracts the corresponding real and imaginary components, and returns a new Complex object with the result.

We then create two instances of Complex, x and y, and subtract y from x to get a new Complex object z. We output the original complex numbers and the result to the console to confirm that the operator is working correctly.