2018年8月5日 星期日

Operator Overloading as Non-member Functions

Money.cpp

#include "Money.h"

Money::Money(int dollars, int cents) : dollars{dollars}, cents{cents} {}

Money::Money(int total) : dollars {total/100}, cents{total%100}  {}
 

//----DO NOT MODIFY THE CODE ABOVE THIS LINE----
//----WRITE YOUR METHOD DEFINITIONS BELOW THIS LINE----

Money Money::operator+(const Money &p)const{
    int dollars_temp = this->dollars + p.dollars;
    int cents_temp = this->cents + p.cents;
    if(cents_temp > 100.0){
        dollars_temp += cents_temp / 100;
        cents_temp %= 100;
    }
    Money temp(dollars_temp, cents_temp);
    return temp;
}

//----WRITE YOUR METHOD DEFINITIONS ABOVE THIS LINE----



=========================================

Money.h

#ifndef _MONEY_MONEY_H
#define _MONEY_MONEY_H


#include <iostream>

class Money {
    int dollars;
    int cents;
public:
    Money(int dollars, int cents);
    Money(int total);
    int get_dollars() const {return dollars;}
    int get_cents() const {return cents; }
   

    //----DO NOT MODIFY THE CODE ABOVE THIS LINE----
    //----WRITE YOUR METHOD DECLARATIONS BELOW THIS LINE----
    Money operator+(const Money &p)const;


   
    //----WRITE YOUR METHOD DECLARATIONS ABOVE THIS LINE----
    //----DO NOT MODIFY THE CODE BELOW THIS LINE----
};


#endif //_MONEY_MONEY_H

沒有留言:

張貼留言