Modify the person class in the PERSORT program in this chapter so that it includes not
only a name, but also a salary item of type float representing the person’s salary.You’ll need to change the setName() and printName() member functions to setData() and printData(), and include in them the ability to set and display the salary as well as the name. You’ll also need a getSalary() function. Using pointer notation, write a salsort() function that sorts the pointers in the persPtr array by salary rather than by name. Try doing all the sorting in salsort(),rather than calling another function as
PERSORT does. If you do this, don’t forget that -> takes precedence over *,so you’ll need
to say
if( (*(pp+j))->getSalary() > (*(pp+k))->getSalary() )
{ /* swap the pointers */ }
1
Expert's answer
2015-02-10T10:57:29-0500
#include <stdlib.h> #include <iostream> #include <stdio.h> #include <cstdlib> #include <string> using namespace std; class Person{ public: void SetData(string newName, float newSalary) { name = newName; salary = newSalary; } void PrintData() { cout<<"-------------------------------------"<<endl; cout<<"Name : "<<name<<endl; cout<<"Salary : "<<salary<<endl; cout<<"-------------------------------------"<<endl; } float GetSalary(){ return salary; } private: string name; float salary; }; void salsort(Person *person, int size); int main(){ Person *sal = new Person[5]; string _name; float _salary; for(int i = 0; i < 3; i++) { system("cls"); cout<<"Enter name : "; cin>>_name; cout<<"Enter salary : "; cin>>_salary; (sal +i)->SetData(_name, _salary); } salsort(sal, 3); system("cls"); for (int i = 0; i < 3; i++){ (sal +i)->PrintData(); } system("pause"); return 0; } void salsort(Person *person, int size) { Person tmp;
Comments
Leave a comment