Last active
May 8, 2025 17:44
-
-
Save Longwater1234/a8a08ed5c2d433bc1f2178a7b59f2adc to your computer and use it in GitHub Desktop.
Money class in c++
This file contains hidden or 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
#include <iostream> | |
#include <stdexcept> | |
#include <iomanip> | |
class Money { | |
public: | |
// Constructor | |
explicit Money(int64_t cents = 0) : amount(cents) {} | |
// Overloaded operators | |
Money operator+(const Money& other) const { | |
return Money(amount + other.amount); | |
} | |
Money operator-(const Money& other) const { | |
return Money(amount - other.amount); | |
} | |
Money operator*(int multiplier) const { | |
return Money(amount * multiplier); | |
} | |
Money operator/(int divisor) const { | |
if (divisor == 0) throw std::invalid_argument("Division by zero"); | |
return Money(amount / divisor); | |
} | |
// Compound assignment operators | |
Money& operator+=(const Money& other) { | |
amount += other.amount; | |
return *this; | |
} | |
Money& operator-=(const Money& other) { | |
amount -= other.amount; | |
return *this; | |
} | |
Money& operator*=(int multiplier) { | |
amount *= multiplier; | |
return *this; | |
} | |
Money& operator/=(int divisor) { | |
if (divisor == 0) throw std::invalid_argument("Division by zero"); | |
amount /= divisor; | |
return *this; | |
} | |
// Comparison operators | |
bool operator==(const Money& other) const { | |
return amount == other.amount; | |
} | |
bool operator!=(const Money& other) const { | |
return !(*this == other); | |
} | |
bool operator<(const Money& other) const { | |
return amount < other.amount; | |
} | |
bool operator<=(const Money& other) const { | |
return amount <= other.amount; | |
} | |
bool operator>(const Money& other) const { | |
return amount > other.amount; | |
} | |
bool operator>=(const Money& other) const { | |
return amount >= other.amount; | |
} | |
// Stream operators for printing | |
friend std::ostream& operator<<(std::ostream& os, const Money& money) { | |
os << "$" << (money.amount / 100) << "." | |
<< std::setfill('0') << std::setw(2) << (money.amount % 100); | |
return os; | |
} | |
friend std::istream& operator>>(std::istream& is, Money& money) { | |
double dollars; | |
is >> dollars; | |
money.amount = static_cast<int64_t>(dollars * 100); | |
return is; | |
} | |
// Getter for raw amount (optional, for advanced usage) | |
int64_t getCents() const { | |
return amount; | |
} | |
private: | |
int64_t amount; // Store amount in cents to avoid floating-point issues | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment