I'm having trouble with basic class definitions. I have to do this for an online worksheet (it is graded by the online software). The problem I am having issues with is
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 .
and my code is as follows
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
class Player{
public:
string name;
int score;
void setName (string a){
name = a;}
void setScore (int b){
score = b;}
string getName(){
return name;}
int getScore(){
return score;}
};
I'm not really sure where I went wrong with my definition, and help would be appreciated.
From what I can see, the only error is that everything is public. Your name and score variables should be private, which is why you have getName() and getScore() - to retrieve that information.
that didn't solve it,my compiler errors are as follows
c.h:1: error: declaration of 'void Player::setName(std::string)' outside of class is not definition
c.h:2: error: declaration of 'void Player::setScore(int)' outside of class is not definition
c.h:3: error: declaration of 'std::string Player::getName()' outside of class is not definition
c.h:4: error: declaration of 'int Player::getScore()' outside of class is not definition
and my code is as follows (I only changed the string name and int score to private)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
class Player{
public:
void setName (string a){
name = a;}
void setScore (int b){
score = b;}
string getName(){
return name;}
int getScore(){
return score;}
private:
string name;
int score;
};
Yeah I don't know what's up with it, my code outside the class is the same as yours, I guess I will move to another exercise and ask the professor what the problem with the exercise is.