I need help with creating Operator-Overloaded functions please. I tried 2 but I am stuck. (Thank you all for your help last time! I was able to completely finish :] ).
Problem 1: The operator+(const Currency &rhs) will add the 2 dollar amounts, but not the 2 cent amounts, though it keeps the cents from one of them. So, 40.20 + 40.20 = 80.20 (40 Dollars and the 20 cents are entered in separately being "int", wrote it as above for readability display purposes...sorry for the confusion!) // Removed subtraction (Program adds/subtracts correctly if overload operators are removed).
Problem 2: Before I had int Dollars and int Cents, now I just have "Amount". I'm guessing I need to pass in those two, and add them together as one cost [Currency/Amount] and return them as "Amount" and use that?* I'm not too sure, another reason I'm stuck :(.
I can post original public members from previous assignment if needed. I've left in all the old functions of the previous assignment's public members for now.
class Currency { private: int Dollars; int Cents; //string Amount;
public: // Constructor Currency(int Dollars = 0, int Cents = 0); friend Currency operator+(Currency, Currency const &); // Addition
// Get int GetDollars();// Need to be removed int GetCents();// Need to be removed
};
Currency::Currency(int Dollars, int Cents) { this->Dollars = Dollars; this->Cents = Cents;
if(this->Cents >= 100) { this->Dollars += 1; this->Cents -= 100; }
}
Currency operator+(Currency left, Currency const &right) { left.Dollars += right.Dollars; left.Cents += right.Cents; while (left.Cents >= 100) { left.Cents -= 100; left.Dollars += 1; } return left; }
int Currency::GetDollars() { return Dollars; }
int Currency::GetCents() { return Cents; }
int main() {
int currDollars; int currCents; //char answer; cout << "Please enter a dollar amount" << endl; cin >> currDollars; cout << "Please enter a cents amount:" << endl; cin >> currCents; // Creating and initalizing objects instances of Currency class Currency payroll(currDollars, currCents); Currency payroll2(currDollars, currCents); Currency payroll3; // Testing overloaded opertator+ payroll3 = payroll + payroll2; // Displaying test results cout << "Payroll3 Amount:$ " << payroll3.GetDollars() << "." << payroll3.GetCents() << endl << endl; return 0;
}
</pre></code>
mainthat just creates an object, uses the overloaded operator, and (for example) prints out the result to show the problem.