Created
January 18, 2022 15:53
-
-
Save stungeye/ff2960ec2c667264644f331e53881f9d to your computer and use it in GitHub Desktop.
Money Class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Money{ | |
static constexpr int centsPerDollar{100}; | |
int mDollars{0}; | |
int mCents{0}; | |
// Ensure that we never have more than 99 cents. | |
void rollCentsIntoDollars() { | |
int additionalDollars = mCents / Money::centsPerDollar; | |
mDollars += additionalDollars; | |
mCents %= Money::centsPerDollar; | |
} | |
public: | |
Money(int dollars, int cents) | |
: mDollars{dollars}, mCents{cents} | |
{ | |
rollCentsIntoDollars(); | |
} | |
Money() = default; // Required for line 58 (no-arg initialization). | |
// Overloaded stream output (friend) | |
friend std::ostream& operator<<(std::ostream &out, const Money& money) { | |
std::string padding{money.mCents < 10 ? "0" : ""}; | |
out << "$" << money.mDollars << "." << padding << money.mCents; | |
return out; | |
} | |
// Overloaded stream input (friend). Note the out vars. | |
friend std::istream& operator>>(std::istream &in, Money& money) { | |
int dollars, cents; | |
char dollarSign, dot; | |
// Parses input in the form: $m.n (where m and n are integers) | |
in >> dollarSign >> dollars >> dot >> cents; | |
if ((dollarSign != '$') || (dot != '.')) { | |
in.clear(std::ios_base::failbit); // Mark input as failed. | |
} else { | |
money = Money{dollars, cents}; | |
} | |
return in; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment