Share
Explore BrainMass

Overloading Operators C++

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.

#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);

// Overloads the >> operator to input values of type
// Percent.
// Precondition: If ins is a file input stream, then ins
// has already been connected to a file.

friend ostream& operator <<(ostream& outs, const Percent& a_percent);

// Precondition: If ins is a file input stream, then ins
// has already been connected to a file.

friend ostream& operator <<(ostream& outs, const Percent& a_percent);

// Overloads the << operator for output values of type
// Percent.
// Precondition: If outs is a file output stream, then
// outs has already been connected to a file.

private:
int value;
};

// Uses iostream:
istream& operator >>(istream& ins, Percent& the_object)
{
char percent_sign;
ins >> the_object.value;
ins >> percent_sign; // Discards the % sign.
return ins;
}
// Uses iostream:
ostream& operator <<(ostream& outs, const Percent& a_percent)
{
outs << a_percent.value << '%';
return outs;
}

Attachments

Solution Summary

Write a program to test all the member functions and overloaded operators in your class definition.

$2.19