I have encountered a problem when trying to overload the '+' operator to add two Money objects rands and cents.
The error:
I encountered on the console is " 'Money Money::operator+(Money*, Money*)' must take either zero or one argument".
My resolution:
1) I tried to use the two integer values 'rands' and 'cents' in my class to store the result when adding the two money.
2) I also researched another way which was to only pass one object to the function (it seemed to work by not producing the same error, but I had to implement a getMoney() method to recieve the rands and cents individually...)
#include <iostream>
using namespace std;
class Money{
public:
int rands;
int cents;
Money();
Money(int rands,int cents);
Money operator+(Money* obj,Money* obj2){return obj};
};
Money::Money(){
rands = 0;
cents = 0;
}
Money::Money(int randsN, int centsN){
rands = randsN;
cents = centsN;
}
Money Money::operator+(Money *obj , Money *obj2){
obj.rands += obj2.rands;
obj.cents += obj2.cents;
return obj;
}
int main(){
Money totalCash=Money();
Money cash = Money(200,20);
Money cashTwo = Money(100,10);
totalCash = cash + cashTwo;
}
1) FIXES: (Working code)
=========================
//Struct Money
struct Money{
int rands;
int cents;
public:
Money();
Money(int rands,int cents);
Money operator+(const Money&)const; // changed
};
// Operator Overload '+' : Working for adding two Money objects
Money Money::operator+(const Money &obj)const{
int totRands=0;
int totCents=0;
totRands= obj.rands + rands;
totCents= obj.cents + cents;
Money newMoney= Money(totRands,totCents);
return newMoney;
}
Thank you Stackoverflow community.