Home > Cpp > C++ Program to implement Operator Overloading with binary arithmetic op (*,+,-) – Q17

C++ Program to implement Operator Overloading with binary arithmetic op (*,+,-) – Q17

January 17, 2010 Leave a comment Go to comments

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


Advertisement
Categories: Cpp Tags: ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: