Define a class named Money that stores a monetary amount. The class should have two private integer variables, one to store the number of dollars and another to store the number of cents. Add accessor and mutator functions to read and set both member variables. Add another function that returns the monetary amount as a double. Write a program that tests all of your functions with at least two different Money objects.
C++ program code:
#include <iostream>
using namespace std;
//Create a class name,
class Money
{
private:
//Declare variables
int dollars;
int cents;
public:
//Default constructor
Money()
{
dollars = 0;
cents = 0;
}
//Accessor functions getDollars and getCents
//are defined to retrieve the values of dollars and cents.
int getDollars() const {
return dollars;
}
int getCents() const {
return cents;
}
//Mutator functions setDollars and setCents are
//defined to set the values of dollars and cents.
void setDollars(int value) {
dollars = value;
}
void setCents(int value) {
cents = value;
}
//The getAmount function returns the monetary amount as a
//double by adding dollars to cents divided by 100.
double getAmount() const {
return dollars + (static_cast<double>(cents) / 100);
}
};
//Program begins with a main method
int main()
{
// two Money objects are created, money1 and money2.
Money money1;
money1.setDollars(10);
money1.setCents(50);
//Call the methods and display appropriate output
cout << "Money 1: $" << money1.getDollars() << "." << money1.getCents() << endl;
cout << "Amount 1: " << money1.getAmount() << endl;
Money money2;
money2.setDollars(5);
money2.setCents(75);
cout << "Money 2: $" << money2.getDollars() << "." << money2.getCents() << endl;
cout << "Amount 2: " << money2.getAmount() << endl;
return 0;
}
Output of the program code:
Money 1: $10.50
Amount 1: 10.5
Money 2: $5.75
Amount 2: 5.75