Overload Binary operators
Binary operators are + , - , * , / , % etc .These are also called arithmetic operators.
Binary operator is a operator that takes two operands.
#include <iostream>
using namespace std;
class rational
{
private:
int num;
int denum;
public:
rational( ):num(1) , denum (1) //num and denum never zero
{ }
rational(int n, int d):num(n),denum(d)
{ }
void get ( )
{
cout<<"enter numerator ";
cin>>num;
cout<<"enter denomirator";
cin>>denum;
}
void print ( )
{
cout<<num <<"/"<<denum;
}
rational operator + (rational r) // we have to overload + operator
{
rational temp;
temp.num = num * r.denum + denum * r.num ;
temp.denum = denum *r.denum;
return temp;
}
};
void main ( )
{
rational r1(3,4) ,r2(4,5), r3;
r3= r1+r2;
r3.print( );
} // program is end
This is by named temporary object
Now for nameless temprary object
some changes in earlier program after print function
rational operator + ( rational r)
{
int nu , de ;
nu =num * r.denum + denum * r.num ;
de=denum *r.denum;
return rational (nu , de);
}
};
...............................................................................................................................................................................