Download Our Beta Android App And Help Us Build Awesome Stuff!  Download Now.

LEARN Operator Overloading - 2

Category: Notes and Syllabus

Course: B.Tech.

Semester: 4

Same Thing but this time taking help of friend function.
SEE the changes ...

#include <iostream>
//StAn_
using namespace std ;

class data
{
      int A ;

      public :
            data( int a )
            {
                  A = a ;
            }
            friend int operator - ( data D1 ) ;
            friend int operator + ( data D1, data D2 ) ;
};

int operator - ( data D1 )     //We require one object of class here.
{
      return (D1.A + 5) ;
}

int operator + ( data D1, data D2 )    //We require two objects of class here.
{
      int result = D1.A * D2.A ;
      return result ;
}

int main()
{
      int check = 2;
      cout<< -check <<endl ;         //o/p => "-2"

      data D1(15), D2(10) ;

      cout<< -D1 <<endl ;           //o/p => "20"     (15+5)
      cout<< D1+D2 <<endl ;         //o/p => "150"    (15*10)

      return 0;
}

Added by StAn

Comments