#ifndef MONEY_H
#define MONEY_H
usingnamespace std;
#include <iostream>
#include <iomanip>
class Money
{
private:
int dollars;
int cents;
public:
Money()
{
setDollars(0);
setCents(0);
}
Money(int dollars, int cents)
{
setDollars(dollars);
setCents(cents);
}
int getDollars() { return dollars; }
int getCents() { return cents; }
void setDollars(int dollars) { this->dollars = dollars; }
void setCents(int cents) { this->cents = cents; }
void prompt()
{
int dollars;
int cents;
cout << "Dollars: ";
cin >> dollars;
cout << "Cents: ";
cin >> cents;
setDollars(dollars);
setCents(cents);
}
// Here is my problem
friendvoid display(Money &money);
};
void display(Money &money)
{
cout << "$" << money.dollars << ".";
cout << setfill('0') << setw(2) << money.cents;
}
#endif
// This is my main:
#include <iostream>
usingnamespace std;
#include "money.h"
/****************************************************************
* Function: main
* Purpose: Test the money class and practice operators
****************************************************************/
int main()
{
Money account1;
Money account2;
// Get the input from the user
account1.prompt();
account2.prompt();
cout << endl;
display(account1);
cout << endl;
display(account2);
return 0;
}
I am getting this error " In function `display(Money&)':
check12a.cpp:(.text+0x0): multiple definition of `display(Money&)'
money.o:money.cpp:(.text+0x0): first defined here
collect2: ld returned 1 exit status"
The problem here is that you are including money.h in both your main.cpp file and money.cpp file, and in money.h you are defining the display function. Thus both main and money end up defining the display function which confuses the linker.
I hope you understand this concept.
If declaring on my money.cpp as void Money::display(Money &money) I get this error
money.cpp:31: error: no ‘void Money::display(Money&)’ member function declared in class ‘Money’
make: *** [money.o] Error 1
but declaring just as void display(Money & money) I get this error:
money.cpp: In function ‘void display(Money&)’:
money.cpp:31: error: redefinition of ‘void display(Money&)’
money.h:59: error: ‘void display(Money&)’ previously defined here
money.h:18: error: ‘int Money::dollars’ is private
money.cpp:33: error: within this context
money.h:19: error: ‘int Money::cents’ is private
money.cpp:34: error: within this context