Archive
Archive for January 17, 2010
C++ Program to implement Operator Overloading with binary arithmetic op (*,+,-) – Q17
January 17, 2010
Leave a comment
Q17. Program to implement Operator Overloading -with binary arithmetic op (*,+,-):
Define a class complex with two data members real & imag.
Perform the following operations:
– Find the sum of two complex numbers
– Find the difference of two complex numbers
– Find the Product of two complex numbers
– Find the Product of a complex number with a constant
… from College notes (BCA/MCA assignments):
#include <iostream.h> #include <conio.h> class Ccomplex{ private: double real, img; public: Ccomplex(){} Ccomplex(double r, double i){ real = r; img = i; } friend Ccomplex operator+(Ccomplex &, Ccomplex &); friend Ccomplex operator-(Ccomplex &, Ccomplex &); friend Ccomplex operator*(Ccomplex &, Ccomplex &); friend Ccomplex operator*(Ccomplex &, double); friend ostream& operator<<(ostream &, Ccomplex &); friend istream& operator>>(istream &, Ccomplex &); }; Ccomplex operator+(Ccomplex &c1, Ccomplex &c2){ return Ccomplex(c1.real + c2.real, c1.img + c2.img); } Ccomplex operator-(Ccomplex &c1, Ccomplex &c2){ return Ccomplex(c1.real - c2.real, c1.img - c2.img); } Ccomplex operator*(Ccomplex &c1, Ccomplex &c2){ return Ccomplex(c1.real * c2.real, c1.img * c2.img); } Ccomplex operator*(Ccomplex &c1, double num){ return Ccomplex(c1.real * num, c1.img * num); } ostream& operator<<(ostream &Mout, Ccomplex &Oc){ return Mout<<"\n Real: "<<Oc.real<<"\n Img: "<<Oc.img; } void main(){ Ccomplex Oc; Ccomplex Oc1(3.1, 4.1); Ccomplex Oc2(4.2, 5.7); double num= 10; clrscr(); cout<<"\n Sum of two Complex No's:- "; Oc = Oc1 + Oc2; cout<<Oc; cout<<"\n\n Difference of two Complex No's:- "; Oc = Oc1 - Oc2; cout<<Oc; cout<<"\n\n Product of two Complex No's:- "; Oc = Oc1 * Oc2; cout<<Oc; cout<<"\n\n Product of Complex No with Constant:-"; Oc = Oc1 * num; cout<<Oc; getch(); }
Output:
Sum of two Complex No’s:-
Real: 7.3
Img: 9.8
Difference of two Complex No’s:-
Real: -1.1
Img: -1.6
Product of two Complex No’s:-
Real: 13.02
Img: 23.37
Product of Complex No with Constant:-
Real: 31
Img: 41
Categories: Cpp
Cpp, Operator Overloading