In: Computer Science
c++ problem:
Implement a class money. You must have friend functions for I/O that overload << and >>. You must have multiple constructors, You must implement a percentage method,+,-, <,>. There is a starting money class in your text.
Example output:
Enter an amount of money: $14.33
Your amount is $14.33
My amount is $10.09
One of us is richer.
You have more money than me.
10% of your money is: $$1.43
$14.33 + $10.09 equals $24.42
$14.33 - $10.09 equals $4.24
Press any key to continue . . .
Here is the code:
#include <iostream>
using namespace std;
class Money
{
private:
double money;
public:
Money(){}
Money(double a)
{
money = a;
}
friend ostream
&operator << (ostream &out, const Money
&m);
friend istream
&operator >> (istream &in, Money &m);
friend Money operator
%(const Money &m1, const Money &m2);
friend Money operator
+(const Money &m1, const Money &m2);
friend Money operator
-(const Money &m1, const Money &m2);
friend bool operator
<(const Money &m1, const Money &m2);
friend bool operator
>(const Money &m1, const Money &m2);
double getMoney() const
{ return money;}
};
ostream &operator <<(ostream &out, const Money
&m)
{
out << m.getMoney();
return out;
}
istream &operator >> (istream &in, Money
&m)
{
in >> m.money;
return in;
}
Money operator%(const Money &m1, const Money &k)
{
return Money(m1.money*k.money/100);
}
Money operator+(const Money &m1, const Money &m2)
{
return Money(m1.money + m2.money);
}
Money operator-(const Money &m1, const Money &m2)
{
return Money(m1.money - m2.money);
}
bool operator<(const Money &m1, const Money &m2)
{
if(m1.money < m2.money) return true;
else return false;
}
bool operator>(const Money &m1, const Money &m2)
{
if(m1.money > m2.money) return true;
else return false;
}
int main()
{
Money yourmoney, mymoney;
cout << "Enter amount of your money:
";
cin >> yourmoney;
cout << "Enter amount of my money:
";
cin >> mymoney;
//Implementation of > operator
cout<< "One of us is richer." <<
endl;
Money m1(yourmoney), m2(mymoney);
if(m1>m2)
{
cout<<"You have
more money than me"<<endl;
}
else
{
cout<<"You have
less money than me"<<endl;
}
//Implementation of % operator
//k% of your money is:
Money k(10);
cout<< k.getMoney()<< "% of your
money is $$"<<(m1%k).getMoney() <<endl;
//implementation of addition operator
Money sum = m1 + m2;
cout<< "$"<<m1.getMoney()<<" +
"<< "$"<< m2.getMoney() <<" equals
"<<sum.getMoney()<<"$"<<endl;
//implementation of subtraction operator
Money sub = m1 - m2;
cout<< "$"<<m1.getMoney()<<" -
"<< "$"<< m2.getMoney() <<" equals
"<<sub.getMoney()<<"$"<<endl;
return 0;
}
//here is the output sample:

//Another sample output:
