Self-Test Exercise 18 asked you to overload the operator>> and the operator<< fo
ID: 3537065 • Letter: S
Question
Self-Test Exercise 18 asked you to overload the operator>> and the operator<< for a class Percent. Complete and test this exercise. Implement the default constructor and the constructor with one int parameter. Overload the + and - operators to add and subtract percents. Also, overload the * operator to allow multiplication of a percent by an integer.
Write a program to test all the member functions and overloaded operators in your class definition.
SELF-TEST EXERCISE 18:
#include <iostream>
using namespace std;
class Percent
{
publc:
friend bool operator==(const Percent& first, const Percent& second);
friend bool operator<(const Percent& first, cons Percent& second);
Percent();
Percent(int percent_value);
friend istream& operator >>(istream& ins, Percent& the_object);
friend ostream& operator<<(ostream& outs, const Percent& a_percent);
private:
int value;
};
Explanation / Answer
#include <iostream>
using namespace std;
class Percent
{
public:
friend bool operator==(const Percent& first, const Percent& second);
friend bool operator<(const Percent& first, const Percent& second);
Percent();
Percent(int percent_value);
friend istream& operator >>(istream& ins, Percent& the_object);
friend ostream& operator<<(ostream& outs, const Percent& a_percent);
Percent operator+(Percent obj);
Percent operator-(Percent obj);
Percent operator*(int n);
private:
int value;
};
Percent::Percent()
{
value=0;
}
Percent::Percent(int percent_value)
{
value=percent_value;
}
istream& operator >>(istream& ins, Percent& the_object)
{
ins>>the_object.value;
return ins;
}
ostream& operator<<(ostream& outs, const Percent& a_percent)
{
outs<<a_percent.value;
return outs;
}
bool operator==(const Percent& first, const Percent& second)
{
if(first.value==second.value)
return true;
else
return false;
}
bool operator<(const Percent& first, const Percent& second)
{
if(first.value<second.value)
return true;
else
return false;
}
Percent Percent::operator +(Percent obj)
{
Percent temp=value+obj.value;
return temp;
}
Percent Percent::operator -(Percent obj)
{
Percent temp=value-obj.value;
return temp;
}
Percent Percent::operator*(int n)
{
Percent temp=value*n;
return temp;
}
int main()
{
Percent obj1;
Percent obj2;
cout<<"Enter the value for object 1 :";
cin>>obj1;
cout<<"Enter the value for object 2 :";
cin>>obj2;
cout<<"object 1: "<<obj1<<endl;
cout<<"object 2: "<<obj2<<endl;
cout<<"object 1 + object 2: "<<obj1+obj2<<endl;
cout<<"object 1 - object 2: "<<obj1-obj2<<endl;
cout<<"object 1 * 2: "<<obj1*2<<endl;
system("pause");
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.