Thursday, May 9, 2013

Operator Overloading – [Simplification] C++



Use of Operator Overloading for simplification.



Example :

 #include<iostream.h>

   //  a/b+c/d using operater overloading

  class OppOvl
      {
           private:
              float num,deno;
           public:
              OppOvl()
                   {
                        num=0;
                        deno=1;
                   }

           void input()
              {
                   cout<<"\t\nEnter Numerator : ";
                   cin>>num;
                   cout<<"\t\nEnter Denominator : ";
                   cin>>deno;
              }

           void display()
              {
                   cout<<"\t "<<num<<" / "<<deno;
              }

           int GCD(int a,int b)
              {
                   int c;
                   while(b>0)
                        {
                            c=a%b;
                            a=b;
                            b=c;
                        }
                   return a;
              }

           OppOvl operator +(OppOvl);

      };
  OppOvl OppOvl::operator + (OppOvl m)
      {
           int g;
           OppOvl m1;
           m1.num=num*m.deno+deno*m.num;
           m1.deno=deno*m.deno;
           if(m1.num>m1.deno)
              {
                   g=GCD(m1.num,m1.deno);
              }
           else
              {
                   g=GCD(m1.deno,m1.num);
              }
           m1.num=m1.num/g;
           m1.deno=m1.deno/g;
           return m1;
      }

  int main()
      {
          OppOvl a,b,c;
           cout<<"\t\nEnter First Exp. ";
           a.input();
           cout<<"\t\nEnter Second Exp. ";
           b.input();
           cout<<"\t\nAfter a + b\n";
           a.display();
           cout<<" + ";
           b.display();
           cout<<" = ";
           c=a+b;
           c.display();
           return 0;
      }

No comments: