Class with public functions?
Oct 22, 2017 at 11:12pm UTC
I need to add a public member function (
addMoney
) to add money1 and money2. I'm having a hard time understanding how to access the function with money1 and money2? Also, my professor wants the addMoney function in that format, and I have no experience with a function in a class this way? The name of the class inside of the function AND before the function name? I really don't understand what's going on with that. Any help is greatly appreciated!! Thanks
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
#include <iostream>
#include <iomanip>
using namespace std;
class Money
{
private :
int dollars;
int cents;
public :
//Constructor #1
Money()
{
dollars = 0;
cents = 0;
}
//Constructor #2
Money(int d, int c)
{
dollars = d;
cents = c;
}
int getDollars(int ) const
{
return dollars;
}
int getCents(int ) const
{
return cents;
}
Money addMoney(Money otherMoney) const
{
Money result;
return result;
}
};
int main()
{
Money money1(10, 25);
Money money2;
money2.getDollars(20);
money2.getCents(10);
system("pause" );
return 0;
}
Last edited on Oct 23, 2017 at 2:28am UTC
Oct 23, 2017 at 7:12am UTC
How about this:
1 2 3 4 5 6 7 8 9
Money addMoney(Money otherMoney) const
{
Money result;
result.dollars = dollars + otherMoney.dollars;
result.cents = cents + otherMoney.cents;
return result;
}
Note that adding cents may exceed 100 cents (i.e. -> dollar).
Used like so:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
...
int getDollars(int ) const
{
return dollars;
}
int getCents(int ) const
{
return cents;
}
...
int main()
{
Money money1(10, 25);
Money money2(20, 10);
Money money3 = money1.addMoney(money2);
cout << "money3: " << money3.getDollars() << "." << money3.getCents();
system("pause" );
return 0;
}
The name of the class inside of the function AND before the function name?
It is the return type like int.
Last edited on Oct 23, 2017 at 7:21am UTC
Oct 25, 2017 at 1:56am UTC
Thank you sooo much!! I understand now Money addMoney
function.
Topic archived. No new replies allowed.