Operator Overloading

Program:


    #include<iostream.h>
    #include<conio.h>
    #inclde<iomanip.h>
class complex { float real,imag; public: complex() { real=0; imag=0; } void read(); void write(); friend complex operator+(complex c1,complex c2); friend complex operator-(complex c1,complex c2); friend complex operator*(complex c1,complex c2); friend complex operator/(complex c1,complex c2); }; void complex::read() { cout<<setw(10)<<"\tEnter the real part: "; cin>>real; cout<<setw(10)<<"\n\tEnter the imaginary part: "; cin>>imag; } void complex::write() { if(imag>1) cout<<setw(10)<<real<<"+"<<imag<<"i"<<endl; else cout<<setw(10)<<real<<" "<<imag<<"i"<<endl; } complex operator+(complex c1,complex c2) { complex t; t.real=c1.real+c2.real; t.imag=c1.imag+c2.imag; return(t); } complex operator-(complex c1,complex c2) { complex t; t.real=c1.real-c2.real; t.imag=c1.imag-c2.imag; return(t); } complex operator*(complex c1,complex c2) { complex t; t.real=(c2.real*c1.real)-(c2.imag*c1.imag); t.imag=(c2.imag*c1.real)-(c2.real*c1.imag); return(t); } complex operator/(complex c1,complex c2) { complex t; t.real=(c1.real*c2.real+c1.imag*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag); t.imag=(c1.imag*c2.real-c1.real*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag); return(t); } void main() { complex c1,c2,c3,c4,c5,c6; char c="Y"; clrscr(); do{ cout<<" "<<setw(10)<<"\n\nEnter the first complex number \n\n\n"; c1.read(); cout<<" "<<setw(10)<<"\n\nEnter the second complex number \n\n\n"; c2.read(); c3=c1+c2; c4=c1-c2; c5=c1*c2; c6=c1/c2; clrscr(); cout<<"\nINPUT : \n\n"; cout<<"\n\n\tFIRST COMPLEX NUMBER : "; c1.write(); cout<<"\n\n\tSECOND COMPLEX NUMBER : "; c2.write(); cout<<"\nOUTPUT : \n\n"; cout<<"\n\tCOMPLEX ADDITION : "; c3.write(); cout<<"\n\tCOMPLEX SUBTRACTION : "; c4.write(); cout<<"\n\tCOMPLEX MULTIPLICATION : "; c5.write(); cout<<"\n\tCOMPLEX DIVISION : "; c6.write(); cout<<setw(10)<<"\n\n DO YOU WANT TO CONTINUE "; c=getche(); } while(c!='n'&&c!='N'); getch(); }
Powered by nasrullah.in - TechnoNasr 2003-2020.
Designed & Developed by Mohamed Nasrullah.M