Design a C++ PayRoll class
Payroll
Design a C++ PayRoll class that has data members for an employees hourly pay rate,
number of hours worked, and total pay for the week. Write a program with an array
of seven PayRoll objects. The program should ask the user for the number of hours
each employee has worked and will then display the amount of gross pay each has
earned.
Input Validation Do not accept values greater than 60 for the number of hours
worked.
Answer:
Payroll
#include <iostream> #include <iomanip> #include "Payroll.h" using namespace std; // Constant for number of employees const int NUM_EMPLOYEES = 7; int main() { double hours; // Hours worked double rate; // Hourly pay rate int count; // Loop counter // Array of Payroll objects Payroll employees[NUM_EMPLOYEES]; // Get the hours worked and the pay rate // for each employee. cout << "Enter the hours worked and pay rate " << "for " << NUM_EMPLOYEES << " employees:\n"; for (count = 0; count < NUM_EMPLOYEES; count++) { // Get the employee's pay rate. cout << "\nEmployee #" << (count+1) << " pay rate: "; cin >> rate; employees[count].setPayRate(rate); // Get the employee's hours worked cout << "Employee #" << (count+1) << " hours worked: "; cin >> hours; employees[count].setHours(hours); } // Display the total pay for each employee. cout << "Total pay:\n"; cout << setprecision(2) << fixed << showpoint << right; for ( count = 0; count < NUM_EMPLOYEES; count++) { cout << "\tEmployee #" << (count+1) << ": "; cout << setw(8) << employees[count].getTotalPay() << endl; } return 0; }
Implementation file for the Payroll class
#include <iostream> #include <cstdlib> #include "Payroll.h" using namespace std; void Payroll::setHours(double h) { if (h > 60) { // Bad number of hours. cout << "Invalid number of hours.\n"; exit(EXIT_FAILURE); } else hours = h; }
Specification file for the Payroll class
Payroll.h
#ifndef PAYROLL_H #define PAYROLL_H class Payroll { private: double hours; double payRate; public: // Constructor Payroll() { hours = 0; payRate = 0; } // Mutators void setHours(double); void setPayRate(double r) { payRate = r; } // Accessors double getHours() const { return hours; } double getPayrate() const { return payRate; } double getTotalPay() const { return hours * payRate; } }; #endif
Leave a reply