Write a Money class (stored in paise) with an implicit constructor from rupees and hidden-friend operators +, −, ==, < and <<, so that mixed expressions like 100 + m work.
Solution
main.cpp
#include <algorithm>
#include <iostream>
#include <vector>
class Money {
long long paise_;
public:
Money(double rupees = 0) : paise_(static_cast<long long>(rupees * 100 + (rupees < 0 ? -0.5 : 0.5))) {}
friend Money operator+(Money a, Money b) { Money r; r.paise_ = a.paise_ + b.paise_; return r; }
friend Money operator-(Money a, Money b) { Money r; r.paise_ = a.paise_ - b.paise_; return r; }
friend bool operator==(Money a, Money b) { return a.paise_ == b.paise_; }
friend bool operator<(Money a, Money b) { return a.paise_ < b.paise_; }
friend std::ostream& operator<<(std::ostream& os, Money m) {
long long p = m.paise_ < 0 ? -m.paise_ : m.paise_;
return os << (m.paise_ < 0 ? "-" : "") << "Rs " << p / 100 << '.' << (p % 100 < 10 ? "0" : "") << p % 100;
}
};
int main() {
Money rent(12500.50), bill(899.99);
Money total = rent + bill + 100; // Money + Money + int
Money left = 15000 - total; // int - Money
std::vector<Money> v{bill, rent, 50};
std::sort(v.begin(), v.end());
std::cout << total << " | " << left << " | " << (bill + 0.01 == 900) << " | "
<< v.front() << ' ' << v.back() << '\n';
return 0;
}
Because the operators are non-member friends, both operands may be converted from numbers: 15000 − total and bill + 0.01 == 900 work. Storing paise avoids floating-point rounding errors in money arithmetic.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!