In: Computer Science
c++
using class...
define operator overloading and give simple example how we can use
operator overloading by writing simple program in which different
operators are used to add, subtract, multiply and division.
C++ allow to specify more than one definition for an operator in the same scope, which is called operator overloading.
Example C++ Program
#include<iostream>
using namespace std;
class Fraction{
private:
int num;
int deno;
public:
Fraction(int n=0 , int d=1){
num = n;
deno = d;
}
Fraction operator+ (const
Fraction& frac) {
Fraction ob;
ob.num = num*frac.deno + deno*frac.num;
ob.deno = deno*frac.deno;
return ob;
}
Fraction operator-
(const Fraction& frac) {
Fraction ob;
ob.num = num*frac.deno - deno*frac.num;
ob.deno = deno*frac.deno;
return ob;
}
Fraction operator*
(const Fraction& frac) {
Fraction ob;
ob.num = num*frac.num;
ob.deno = deno*frac.deno;
return ob;
}
Fraction operator/
(const Fraction& frac) {
Fraction ob;
ob.num = num*frac.deno;
ob.deno = deno*frac.num;
return ob;
}
friend ostream&
operator << (ostream& out , const Fraction&
Frac){
out<<Frac.num<<"/"<<Frac.deno<<endl;
return
out;
}
};
int main(){
Fraction F1(2,3);
Fraction F2(1,2);
cout<<"F1 + F2 = "<< F1 +
F2<<endl;
cout<<"F1 - F2 = "<<F1 -
F2<<endl;
cout<<"F1 * F2 = "<<F1 *
F2<<endl;
cout<<"F1 / F2 = "<<F1 /
F2<<endl;
return 0;
}
sample output