11: Classes and Objects Question 1: CS2311 – Yang, QingXiong

advertisement
CS2311 – Yang, QingXiong
11: Classes and Objects
Question 1:
You are to write a class called NBAPlayer that represents a professional basketball player in
NBA. An NBA player has the following attributes: family name, first name, position, and salary.
The class thus has 4 data members, where family name and first name are cstrings that can
hold up to 15 English characters; position is an integer that can be 1, 2, 3, 4, or 5, being Center,
Power Forward, Small Forward, Shooting Guard, and Point Guard, respectively; and salary is a
double variable in terms of million USD.
For example:
Kobe Bryant is playing as a shooting guard earning $30.5 million USD in 2013. The family
name is “Bryant”, first name is “Kobe”, position is 4, and salary is 30.5.
The NBAPlayer class shall have the following public member functions:
1. A constructor with 4 parameters (for initialization of member variables).
2. A member function, getSalary(), which returns the salary of a player as a double
number (e.g. 3.6 for a player earning $3.6 million USD.)
3. A member function, printName(), that prints firstname followed by a space and then
familyname.
According to the requirements above, answer the following questions.
(a) Complete the class definition of NBAPlayer (Do not add any extra member). You only
need to provide function prototypes.
class NBAPlayer
{
public:
// complete the function prototypes here
private:
char familyname[ ]; // complete the array size
char firstname[ ]; // complete the array size
int position;
CS2311 – Yang, QingXiong
double salary;
};
(b) The default constructor is not given in (a). Jack says, "No problem. A default constructor will
be generated for us automatically". Is Jack correct? Please try to explain.
(c) You are to implement a non-member function, sortPlayers, which sorts an array of
players according to their salaries in a descending order.
You also need to complete the given main function such that the program outputs the result as
given below (Salary is printed with one decimal point):
Kobe Bryant ($30.5 million USD)
Joe Johnson ($21.5 million USD)
Dwight Howard ($20.5 million USD)
LeBron James ($19.0 million USD)
Chris Paul ($18.7 million USD)
The NBAPlayer class should not be modified. You can assume there are 5 players in the array.
You can also assume that all member functions of the class are implemented correctly and can
be directly used.
void sortPlayers(NBAPlayer players[],int nr_player)
{
}
void main()
{
const int TOTAL = 5;
NBAPlayer p[TOTAL] = {
NBAPlayer("Bryant", "Kobe", 4, 30.5),
NBAPlayer("James","LeBron", 3, 19),
NBAPlayer("Johnson","Joe", 4, 21.5),
NBAPlayer("Howard","Dwight", 1, 20.5),
NBAPlayer("Paul","Chris", 5, 18.7)
};
//Call the sortPlayers function:
//Display the sorted players and their information
}
Download