A function can be "overloaded" by changing its signature, that is by changing the types or numbers of parameters. It is the data type that matters not the variable name. Additionally the order of the parameters does not count. So (double, int) is the same as (int, double) as far as the compiler is concerned.
We also used separated the function prototypes from the function bodies again using header files.
Here is the header file:
Payrollheader.h
double GetPay(double rate, int hours);
double GetPay(double salary);
double GetPay(double contractAmt, double percent);
Here is the function definition file
PayrollFunctions.cpp
double GetPay(double rate, int hours)
{
double pay=0;
if (hours >40)
{
pay=rate * (hours+((hours-40) * 1.5));
}
else
{
pay=rate*hours;
}
return pay;
}
double GetPay(double salary)
{
return salary / 52;
}
double GetPay(double contractAmt, double percent)
{
return contractAmt * percent;
}
And here is the program file which calls each overloaded version of the GetPay() function:
Program.cpp
#include <iostream>
#include "PayrollHeader.h"
using namespace std;
int main()
{
cout << "how many hours did you work? "<< endl;
int hours;
cin >> hours;
cout << "What was your hourly rate?"<<endl;
double rate;
cin >> rate;
cout << "Your weekly pay is " << GetPay(rate,hours) << endl;
cout << "*************************************" <<endl;
cout << "What is your annual salary?" << endl;
double sal;
cin >> sal;
cout << "Your weekly pay is " << GetPay(sal) <<endl;
cout << "*************************************" <<endl;
cout << "What is your total contract amount?" << endl;
double cAmt;
cin >>cAmt;
cout << "What percent is this week of your contract? " << endl;
double prct;
cin >> prct;
double pay=GetPay(cAmt,prct);
cout << "Your weekly pay is " << pay << endl;
char c;
cin >> c;
}
No comments:
Post a Comment