112k views
2 votes
Write a full class definition for a class named Player , and containing the following members:

A data member name of type string .
A data member score of type int .
A member function called setName that accepts a parameter and assigns it to name . The function returns no value.
A member function called setScore that accepts a parameter and assigns it to score . The function returns no value.
A member function called getName that accepts no parameters and returns the value of name .
A member function called getScore that accepts no parameters and returns the value of score .

This is what I have, aparently this is wrong:

class Player
{
private:
string name;
int score;
public:
void Player::setName (string n)
{
name =n;
}

void Player::setScore (int s)
{
score = s;
}


string Player::getName ()
{
return name;
}


int Player::getScore ()
{
return score;
}


};

2 Answers

2 votes

Final answer:

The corrected class definition removes the unnecessary class scope 'Player::' from the member function implementations and exposes proper function signatures for 'setName', 'setScore', 'getName', and 'getScore' within the class definition.

Step-by-step explanation:

The class definition provided for the Player class has a couple of issues that need to be corrected. First, it is unnecessary to prefix member function definitions with Player:: inside the class definition. Second, the constructor is not defined. Below is the corrected full class definition:

class Player {
private:
string name;
int score;
public:
void setName(string n) {
name = n;
}
void setScore(int s) {
score = s;
}
string getName() const {
return name;
}
int getScore() const {
return score;
}
};

This definition includes the private data members name and score along with the necessary member functions for setting and retrieving these values.

User Jevgeni
by
5.6k points
5 votes

Final answer:

Corrected the provided Player class code by removing unnecessary scoping and ensuring proper syntax inside the class definition.

Step-by-step explanation:

The code you have provided for the Player class has a few issues with the function definitions outside the class scope. In C++, you do not need to specify the class name with the scope resolution operator when defining member functions inside the class definition. Here is the corrected version of the code:

class Player {
private:
string name;
int score;

public:
void setName(string n) {
name = n;
}

void setScore(int s) {
score = s;
}

string getName() const {
return name;
}

int getScore() const {
return score;
}
};
Remember to include the header '<string>' to use the string type and use 'const' at the end of getter functions to indicate that they do not modify any member data.
User Wentjun
by
5.7k points