Your task
is to write a class for numeric values that represent monetary amounts. When
you have written and tested the ADT,
you will then incorporate it into your inventory program, to give it a
"real" test. When you have done this, you will understand how to
write an abstract data type and how to use it.
Monetary
amounts are usually just represented by floating-point numbers, as you did in
your original inventory program. However, just using numbers opens up monetary
values to possible misuse. As an ADT, the type float (or double, which is just
a bigger version) can be used with the following operations: +, -, *, /, ==, >, <, >=, <=, and, through
coercion to integers, with %, &&, ||, !, &, |. They can also be
read and written in one of two formats: fixed point, and scientific. Whereas
this all makes sense for general-purpose numbers, when all we really want is to
manipulate money amounts, we would like to restrict the operations that apply.
We can do this with an abstract data type definition, using the class mechanism
in C++.
We would
like to restrict the operations on money amounts to these:
Design
your class to represent money amounts using two components--a whole number
part, and a fractional part. Use a long integer for the first, and a bounded
integer for the second. By bounded we mean that the number of decimal places
will be limited to two at all times. This means only fractional values in the
range 0 to 99 will be allowed. Your ADT will enforce this constraint by suitable
implementation of the overloaded operators described above. The class will then
have three private variables:
class
Money {
private:
long whole;
unsigned char fraction;
char prefixSymbol;
. . .
};
There will
be two ways to construct a Money object: from two integers, and from a float:
Money(long
whole, unsigned char fraction, char prefix = '$');
Money(float
m, char prefix = '$');
Notice the
use of a default parameter for the currency symbol. The other class class members
should implement the operations given in the last section.
Use the following
main function to test your class. Your class must
work with this code, without alteration.
int
main() {
// object creation
Money m1, m2(123.45), m3(234.56);
// input and output
cout << "m1 is " << m1
<<endl;
cin >> m1; // make sure this reads the
value $345.67
cout << "m1 is " << m1
<<endl;
cout << "m2 is " << m2
<<endl;
cout << "m3 is " << m3
<<endl;
// arithmetic
m1 = m2 + m3 * 2;
cout << "m1 is now "
<< m1 << endl;
// division
double ratio = m3 / m2;
cout << "ratio of m3 and m2 is
" << ratio << endl;
// comparision
if (m3 > m2)
cout << "m3 is bigger than
m2" << endl;
else
cout << "m2 is bigger than
m3" << endl;
return 0;
}
Friday,
March 24th at 5 pm.