1 // Money.h 2 #ifndef MONEY_H 3 #define MONEY_H 4 5 #include <string> 6 #include <stdexcept> 7 #include <cppunit/portability/Stream.h> // or <iostream> if portability is not an issue 8 9 class IncompatibleMoneyError : public std::runtime_error 10 { 11 public: IncompatibleMoneyError()12 IncompatibleMoneyError() : std::runtime_error( "Incompatible moneys" ) 13 { 14 } 15 }; 16 17 18 class Money 19 { 20 public: Money(double amount,std::string currency)21 Money( double amount, std::string currency ) 22 : m_amount( amount ) 23 , m_currency( currency ) 24 { 25 } 26 getAmount()27 double getAmount() const 28 { 29 return m_amount; 30 } 31 getCurrency()32 std::string getCurrency() const 33 { 34 return m_currency; 35 } 36 37 bool operator ==( const Money &other ) const 38 { 39 return m_amount == other.m_amount && 40 m_currency == other.m_currency; 41 } 42 43 bool operator !=( const Money &other ) const 44 { 45 return !(*this == other); 46 } 47 48 Money &operator +=( const Money &other ) 49 { 50 if ( m_currency != other.m_currency ) 51 throw IncompatibleMoneyError(); 52 53 m_amount += other.m_amount; 54 return *this; 55 } 56 57 private: 58 double m_amount; 59 std::string m_currency; 60 }; 61 62 63 // The function below could be prototyped as: 64 // inline std::ostream &operator <<( std::ostream &os, const Money &value ) 65 // If you know that you will never compile on a platform without std::ostream 66 // (such as embedded vc++ 4.0; though even that platform you can use STLPort) 67 inline CPPUNIT_NS::OStream &operator <<( CPPUNIT_NS::OStream &os, const Money &value ) 68 { 69 return os << "Money< value =" << value.getAmount() << "; currency = " << value.getCurrency() << ">"; 70 } 71 72 73 #endif 74