Operator Overloading in C++

#include<iostream>

using namespace std;


class Complex {

private:

int real, imag;

public:

Complex(int r = 0, int i = 0){

      real = r; imag = i;

}

Complex operator - (Complex const &obj) {

Complex res;

res.real = real - obj.real;

res.imag = imag - obj.imag;

return res;

}

Complex operator + (Complex const &obj) {

Complex res;

res.real = real + obj.real;

res.imag = imag + obj.imag;

return res;

}

Complex operator * (Complex const &obj) {

Complex res;

res.real = real * obj.real;

res.imag = imag * obj.imag;

return res;

}

Complex operator / (Complex const &obj) {

Complex res;

res.real = real / obj.real;

res.imag = imag / obj.imag;

return res;

}

void print() {

      cout <<"Result is: "<< real << " + i" << imag << '\n';

}

};


int main()

{

Complex c1(10, 5), c2(2, 4);

Complex c3 = c1 + c2;

c3.print();

Complex c4 = c1 - c2;

c4.print();

Complex c5 = c1 * c2;

c5.print();

Complex c6 = c1 / c2;

c6.print();

}


No comments:

Post a Comment

Operator Overloading in C++

#include<iostream> using namespace std; class Complex { private: int real, imag; public: Complex(int r = 0, int i = 0){       re...