Write a code to overloading the comparison operators (== and != ).In this code compaison of complex number.

 


The comparison operator are all binary operator , mainly if you are doing comparison operator output is mainly bool.


#include<iostream>
using namespace std;
//Class definition
class complx
{
private:
int real;
int imag;
public:
complx(){}
complx(int a,int b)
{
real=a;
imag=b;
}
friend bool operator ==(complx &n1,complx &n2);// == operator overload
friend bool operator !=(complx &n1,complx &n2); // Not equal operator overload
void print()
{
cout<<real<<"+"<<imag<<"i"<<endl;
}
};
bool operator ==(complx & n1,complx &n2)
{
return (n1.real==n2.real && n1.imag ==n2.imag);
}
bool operator !=(complx & n1,complx &n2)
{
return (n1.real!=n2.real || n1.imag !=n2.imag);
}
int main()
{
complx c1(1,2),c2(1,2);
c1.print();
c2.print();
complx c3(1,2),c4(4,2);
if(c1==c2)
{
cout<<"Both complex number is equal "<<endl;
}
c3.print();
c4.print();
if(c3!=c4)
{
cout<<"Both numbe is not equal "<<endl;
}
return 0;
}
view raw .cc hosted with ❤ by GitHub
1+2i
1+2i
Both complex number is equal 
1+2i
4+2i
Both numbe is not equal

0 Comments