Operator Overloading for Binary Operatoy(-)

This is the C++ code for subtracting two Complex Numbers by Overloading Binary(-) Operator

#include <iostream>

using namespace std;

class Complex
{
    float real, img ;
public:
    Complex()
    {
        real=0;
        img=0;
    }
    Complex(int x, int y)
    {
        real = x;
        img = y;
    }
    Complex operator-(Complex);
    void print();
};

void Complex::print()
{
    cout << endl << real << "+i" << img << endl ;
}

Complex Complex::operator-(Complex c1)
{
    Complex c;
    c.real = real-c1.real ;
    c.img = img-c1.img ;
    return c;
}

int main()
{
    Complex c1(4,6), c2(6,4);
    Complex c3;
    c3 = c1-c2 ;
    cout << endl << "First complex number=" << endl ;
    c1.print();
    cout << endl << "Second complex number=" << endl ;
    c2.print();
    cout << endl << "Difference=" << endl ;
    c3.print();
    return 0;
}

No comments:

Post a Comment