1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
|
header file
#include <iostream>
#ifndef MONEY_H
#define MONEY_H
using namespace std;
class money
{
public:
money(int = 0, int = 0);
void setMoney(int, int);
void getMoney(int&, int&) const;
int dollarsToCents() const; // converts $1.05 to 105 cents
bool equalMoney(money otherMoney) const; // checks if two money objects are equal
private:
int dollars;
int cents;
};
ostream & operator<<(ostream& cout, money right);
istream & operator>>(istream& cin, money& right);
money operator+(money, money);
bool operator==(money, money);
bool operator!=(money, money);
#endif
Cpp file
#include "money.h"
#include <iostream>
#include <cassert>
using namespace std;
money::money(int d, int c)
{
dollars = d;
cents = c;
}
void money::setMoney(int d, int c)
{
dollars = d;
cents = c;
}
void money::getMoney(int & d, int & c) const
{
d = dollars;
c = cents;
}
int money::dollarsToCents() const
{
return (dollars * 100 + cents);
}
bool money::equalMoney(money otherMoney) const
{
return (dollars == otherMoney.dollars && cents == otherMoney.cents);
}
ostream & operator<<(ostream& cout, money right)
{
int d, c;
right.getMoney(d,c);
cout << "$" << d << ".";
if (c == 0)
cout << "00";
else if (c < 10)
cout << "0" << c;
else
cout << c;
return cout;
}
istream& operator>>(istream& cin, money& right)
{
int d,c;
char ch;
cin>>d>>ch>>c;
right.setMoney(d,c);
return cin;
}
money operator+(money left, money right)
{
money result;
int rd,ld,rc,lc,resultd,resultc;
left.getMoney(ld,lc);
right.getMoney(rd,rc);
resultd= ld+rd;
resultc=lc+rc;
result.setMoney(resultd,resultc);
return result;
}
bool operator==(money right, money left)
{
return left.dollarsToCents()==right.dollarsToCents();
}
bool operator!=(money left, money right)
{
return left.dollarsToCents()!=right.dollarsToCents();
}
driver
#include<iostream>
#include"money.h"
using namespace std;
int main()
{
money m1;
money m2(10);
int dollar,cent;
cout<<"m1 created with default constructor:\t"<<m1<<endl;
cout<<"m2 created with m2(10):\t"<<m2<<endl;
cout<<"Now enter new value for m1: ";
cin>>m1;
m1.getMoney(dollar,cent);
cout<<"Now, m1 has "<<dollar<<" dollars and "<<cent<<" cents"<<endl;
cout<<"Enter amount of dollars for m2: ";
cin>>dollar;
cout<<"Enter amount of cents for m2: ";
cin>>cent;
m2.setMoney(dollar,cent);
cout<<"m1 + m2 = "<<(m1+m2)<<endl;
cout<<"m1 == m2: "<<(m1==m2)<<endl;
cout<<"m1 != m2: "<<(m1!=m2)<<endl;
system("pause");
return 0;
}
|