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;
}


};

Respuesta :

Answer:

I used C++ to implement this program using dev c++, however, i defined the public method inside the class. The code with illustration of this question is given in section phase. If you want to define the classes outside from class then you can use scope resolution operator to access the method of the class. However, the complete running code is given below in explanation section

Explanation:

#include <iostream>// included preprocessor directive

using namespace std;

class player// class player is started from here

{

private:// class varaibles are set at here and scope of varialbe is private.

 string name;//variable for getting and setting name of player

 int score;//variable for getting and setting score of player

 

public:// declaring public method that can be accessbile outside of class but in this program

 void setName (string name)// public method for setting name of player

{

 this->name=name;// name is initialized by paramenter name to variable name

}

 void setScore(int score)//publice method for setting score of player

{

 this->score=score;

}

int getScore()// public method for getting score of player

{

 return score;// on call, return the score of player

}

string getName()// public method for getting name of player

{

 return name;// return player name;

}

 

};//end of class "player"

int main()//main function get executed

{

   player firstPlayer;//class object "firstPlayer" is created

firstPlayer.setName("Renaldo");// firstPlayer name is initialized

firstPlayer.setScore(500);// assgined score to firstPlayer

string getname=firstPlayer.getName();// get name of firstPlayer

int getscore=firstPlayer.getScore();//get score of firstPlayer

cout<<getname;//print name of firstPlayer

cout<<"\n";//line break

cout<<getscore;//print score of firstPlayer

cout<<"\n";//line break

   

   return 0;//end of program

}