const int CENTS_PER_QUARTER = 25, CENTS_PER_DIME = 10, CENTS_PER_NICKEL = 5;
// The Coins class holds and manipulates a collection of change in
// quarters, dimes, nickels, and pennies.
class Coins
{
private:
int quarters, dimes, nickels, pennies;
public:
/// Constructor; initializes 'this' Coins object
Coins( int q, int d, int n, int p )
: quarters( q ), dimes( d ), nickels( n ), pennies( p )
{
}
// displays 'this' Coins data to out
void print( ostream & out )
{
out << quarters << " quarters, "
<< dimes << " dimes, "
<< nickels << " nickels, and "
<< pennies << " pennies";
}
// takes in an amount of change, removes the appropriate number
// of each coin, and returns a Coins object for the amount
Coins extractChange( int amount )
{
Coins c( 0, 0, 0, 0 );
while ( quarters > 0 && amount >= CENTS_PER_QUARTER )
{
quarters--;
c.quarters++;
amount -= CENTS_PER_QUARTER;
}
while ( dimes > 0 && amount >= CENTS_PER_DIME )
{
dimes--;
c.dimes++;
amount -= CENTS_PER_DIME;
}
while ( nickels > 0 && amount >= CENTS_PER_NICKEL )
{
nickels--;
c.nickels++;
amount -= CENTS_PER_NICKEL;
}
pennies -= amount;
c.pennies = amount;
return c;
}
// takes a Coins object, c, and adds its quarters, dimes, nickels,
// and pennies to the quarters, dimes, nickels, and pennies of
// this Coins object
void depositChange( Coins c )
{
// you write this one
}
};
/// Here is the put operator for class Coins
ostream & operator << ( ostream & out, Coins & c )
{
c.print( out );
return out;
}
/// You must re-write the main program
// Main.cpp
#include "Coins.h"
const int CENTS_FOR_CANDYBAR = 482;
int main()
{
/// The first line creates a Coins object called 'pocket.'
Coins pocket( 100, 10, 10, 100 );
cout << "I started with " << pocket << " in my pocket" << endl;
/// This line creates a Coins object called payForCandy and initializes it.
Coins payForCandy = pocket.extractChange( CENTS_FOR_CANDYBAR );
cout << "I bought a candy bar for " << CENTS_FOR_CANDYBAR
<< " cents using " << payForCandy << endl;
cout << "I have " << pocket << " left in my pocket" << endl;
return 0;
}