In: Computer Science
Write a template class Number with the following
features
Overload following operators for the template class
+
-
<
>
Overload << and >> operators for the ostream and
istream against this class.
Write a main function to demonstrate the functionality of each
operator.
all function and operator has been overloaded through friend function and it is able to produce output of all these
operator
code is below:-
#include <iostream>
using namespace std;
class operation
{
private:
int num;
public:
operation(int r = 0)
{ num = r; }
friend ostream & operator << (ostream &out, const operation &c);
friend istream & operator >> (istream &in, operation &c);
friend operation operator + (operation const &, operation const &);
friend operation operator - (operation const &, operation const &);
friend operation operator > (operation const &, operation const &);
friend operation operator < (operation const &, operation const &);
void print()
{
cout<<num<<endl;
}
};
ostream & operator << (ostream &out, const operation &c)
{ out<<"Entered number is : "<<c.num<<endl;
return out;
}
istream & operator >> (istream &in, operation &c)
{
cout << "Enter Number \n";
in >> c.num;
return in;
}
operation operator + (operation const &c1, operation const &c2)
{
return operation(c1.num + c2.num);
}
operation operator - (operation const &c1, operation const &c2)
{
return operation(c1.num - c2.num);
}
operation operator > (operation const &c1, operation const &c2)
{
if(c1.num>c2.num) return c1.num;
return c2.num;
}
operation operator < (operation const &c1, operation const &c2)
{
if(c1.num<c2.num) return c1.num;
return c2.num;
}
int main()
{
operation c1;
operation c2;
operation c3;
cin >> c1;
cout << c1;
cin>>c2;
cout<<c2;
c3=c1+c2;
cout<<"\n"<<endl;
cout<<"sum is : ";c3.print();cout<<"\n";
c3=c1-c2;
cout<<"Difference is : ";c3.print();cout<<"\n";
c3=c1>c2;
cout<<"Greater is : ";c3.print();cout<<"\n";
c3=c1<c2;
cout<<"Smaller is : ";c3.print();cout<<"\n";
return 0;
}
output is mentioned below
output 2
Explanation :- all declared method operator overloaded function are declared as friend function because this function can access directly private and protected data and methods