Saturday 17 September 2011

Binary operator overloading


Binary operator overloading
Aim:
To write a C++ program to add two complex numbers using binary operator overloading.
Algorithm:
Step 1: Create a class as complex.
Step 2: Declare the data members as real and img.
Step 3: Declare the member functions as
complex()
complex operator +(complex c2)
void read()
void print()
Step 4: Constructor is used to initialize the data members to zero.
Step 5: read() method is used to get the complex numbers.
Step 6: print() method is used to display the complex numbers.
Step 7: operator overloading function is used to perform add operation on complex
numbers.
Step 8: In main, create the object for class complex.
Step 9: Call the binary operator overloading function using the syntax
                         objectname operator objectname
Step10: Add the two complex numbers and display the result.

Program:
#include<iostream.h>
#include<conio.h>

class complex
{
  int real,img;
 public:
       complex()
       {
real=0;
img=0;
       }

       complex operator +(complex c2)
       {
complex c;
c.real=real+c2.real;
c.img=img+c2.img;
return c;
       }

       void read()
       {
cout<<"\n ENTER THE REAL AND THE IMAGINARY PART:";
cin>>real>>img;
       }

       void print()
       {
cout<<real<<"+"<<img<<"i"<<"\n";
       }
};

void main()
{
  clrscr();
  complex c1,c2,c3;
  c1.read();
  c2.read();
  c3=c1+c2;
  cout<<"\n\n";
  cout<<"The Complex Number of C1: ";
  c1.print();
  cout<<"\n\nThe Complex Number of C2: ";
  c2.print();
  cout<<"\n\n THE ADDITION IS:";
  c3.print();
  getch();
}

Output:

 ENTER THE REAL AND THE IMAGINARY PART:6 8

 ENTER THE REAL AND THE IMAGINARY PART:3 4


 THE COMPLEX NUMBER OF C1: 6+8i

 THE COMPLEX NUMBER OF C2: 3+4i

 THE ADDITION IS:9+12i

0 comments:

Post a Comment