1 2 3 4 5 6 7 8 9 10 11 12
|
class Character
{
private:
string name;
int hitPoints;
public:
Character(string = "Thor", int = 100);
void SetName(string);
void ShowName(string); // Here
};
|
Check the line marked with "Here".
In that line, you're passing a std::string parameter you don't really need.
You want to print the hero's name, and you're storing that name inside your class.
You don't need it passed as a parameter.
You also are not editing anything in the class, so you can mark it as constant (const):
You may also want to add some GetName/GetHp.
So, This
1 2 3 4
|
void Character::ShowName(string name)
{
cout << name;
}
|
Becomes This:
1 2 3 4 5
|
void Character::ShowName() const
// const also goes there
{
cout << name;
}
|
In this case, 'name' refers to 'this->name'.
Also, you did the opposite operation in SetName.
1 2 3 4
|
void Character::SetName(string newName)
{
newName = name;
}
|
should be
1 2 3 4
|
void Character::SetName(string newName)
{
name = newName;
}
|
Now for this, your code in 'int main()' will become:
1 2 3 4 5 6
|
// ...
getline(cin, theName);
player1.SetName(theName);
cout << "The next Hero to enter shall be called ";
player1.ShowName(theName);
cout << '!' << endl;
|
You can extend it a little bit by writing this somewhere out of the class and before 'int main()':
(You need GetName, and you need it marked const)
ostream& operator<<(ostream& out, const Character& x ) { return (out << x.GetName()); }
Personally, i'd write it like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
|
class Character
{
private:
string name;
int hitPoints;
public:
Character(string = "Thor", int = 100);
void SetName(string);
void SetHp(int);
string GetName() const;
int GetHp() const;
};
Character::Character(string newname, int hp)
{
name = newname;
hitPoints = hp;
}
void Character::SetName(string newname)
{
name = newname;
}
void Character::SetHp(int hp)
{
hitPoints = hp;
}
string Character::GetName() const
{
return name;
}
int Character::GetHp() const
{
return hitPoints;
}
ostream& operator<<(ostream& out, const Character& x ) { return (out << x.GetName()); }
int main()
{
string theName;
Character player1;
cout << "Enter player name:";
getline(cin, theName);
player1.SetName(theName);
cout << "The next Hero to enter shall be called " << player1 << '!' << endl;
return 0;
}
|
Feel free to explore the code or ask questions about it
(Oh, and usually HP means Health Points, not Hit Points)
Those functions could even be inlined.