Friday, 18 January 2013

Operator overloading in c++


           /************************************/


              #include <iostream>
              #include <conio>
class add
{private:
float a,b;
public:
add()
{
a=b=0;
}
void input()
{
cout<<"ENTER Ist NO=\t";cin>>a;
cout<<"ENTER 2ND NO=\t";cin>>b;
}
void show()
{
cout<<a<<endl;
cout<<b<<endl;
}

          /*******************************/
          add operator +(add p)
{
    add temp;
   temp.a=p.a+a;
  temp.b=p.b+b;
  return temp;
}

    /****************************************/

add operator -(add p)
{
add temp;
temp.a=p.a-a;
temp.b=p.b-b;
return temp;
}

/*********************************************/

add operator *(add p)
{
add temp;
temp.a=p.a*a;
temp.b=p.b*b;
return temp;
}

/*********************************************/
add operator /(add p)
{
add temp;
temp.a=p.a/a;
temp.b=p.b/b;
return temp;
}
/*********************************************/
};
void main()
{

int opt;
add x,y,z;
x.input();
y.input();
 cout<<"First object is";
 cout<<endl;
 x.show();

 cout<<"2nd object is\t\t";
  cout<<endl;
 y.show();


while(1)
{

  cout<<"\t\tPress 1 for + operator overload\n\t\tPress 2 for - operator overload\n\t\tPress 3 for * operator overload\n\t\tpress 4 for / operator overload\n";
  cin>>opt;
switch(opt)
{
  case 1: z=x+y;z.show();break;
  case 2: z=x-y;z.show(); break;
 case 3: z=x-y;z.show();break;
 case 4: z=x/y;z.show();break;
 default:
     cerr<<"\ainvalid option\n";

}


}

getch();
}

0 comments:

Post a Comment