This is a Complex Number Class Definition in C++. The basic Operations on Complex Numbers are defined here also, from taking input to Algebra. And it has a tiny example of Exception Handling for new operator
#include <iostream.h> class complex{ private: float *x,*y; public: complex(float a=0.0, float b=0.0) { try{ x=new float; *x=a; y=new float; *y=b; } catch(...) { cout<<"Memory is not sufficient"; } } complex operator + (complex c){ complex z; *(z.x)=(*x) + *(c.x); *(z.y)=(*y) + *(c.y); return z; } complex operator - (complex c){ // Binary Minus complex z; *(z.x)=(*x) - *(c.x); *(z.y)=(*y) - *(c.y); return z; } complex operator - (){ // Unary Minus complex z; *(z.x)=-(*x); *(z.y)=-(*y); return z; } complex operator * (complex c){ complex z; *(z.x)=(*x)*(*(c.x))-(*y)*(*(c.y)); *(z.y)=(*y)*(*(c.x))+(*x)*(*(c.y)); return z; } complex operator / (complex c){ complex z; float t; t=(*(c.x))*(*(c.x)) + (*(c.y))*(*(c.y)); *(z.x)=((*x)*(*(c.x)) + (*y)*(*(c.y)))/t; *(z.y)=((*y)*(*(c.x)) - (*x)*(*(c.y)))/t; return z; } friend ostream & operator << (ostream &o,complex c); friend istream & operator >> (istream &i,complex c); }; ostream & operator << (ostream &o,complex c){ if (*(c.y)>=0.0) o<<*(c.x)<<"+"<<*(c.y)<<"i"; else o<<*(c.x)<<*(c.y)<<"i"; return o; } istream & operator >> (istream &i,complex c){ cout<<"(Real Part):: "; i>>*(c.x); cout<<"(Img. Part):: "; i>>*(c.y); return i; } void main() { complex a,b,c; cout<<"Enter complex Number 1:: "; cin>>a; cout<<"Enter complex Number 2:: "; cin>>b; cout<<"The Complex Numbers are::\nA="<<a<<endl<<"B="<<b; cout<<"\n-B="<<-b; //Negetive of Complex Number cout<<"\nA+B="<<a+b; //Addition of Complex Numbers cout<<"\nA-B="<<a-b; //Subtraction of Complex Numbers cout<<"\nAxB="<<a*b; //Multiplication of Complex Numbers cout<<"\nA/B="<<a/b; //Division of Complex Numbers }
This may not run on all Turbo C++ Compiler due to exception handling code.
Comments