I'm brand new to C++ and am having a few problems with my basic understanding of how scoping works. I've done searches and am going through the tutorials section but if someone could tell me what I'm doing wrong here I think it would help my understanding immensely.
I'm trying to ascertain and then set a player's name for a specific instantiation of the class Player. The classes are a bit convoluted, as I intend to do much more in the long run.
||=== Build: Debug in myGame (compiler: GNU GCC Compiler) ===|
C:\Users\.....\Player.cpp||In function 'void playerIntro()':|
C:\Users\.....\Player.cpp|16|error: 'setPlayerName' was not declared in this scope|
C:\Users\.....\Player.cpp||In function 'void setPlayerName(std::string)':|
C:\Users\.....\Player.cpp|22|error: '_name' was not declared in this scope|
||=== Build failed: 2 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
setPlayerName and _name are both declared in the header and I only want to set the player name for that particular Player object.
I would appreciate some advise on why these are out of scope and how to declare them in scope.
Thanks in advance.
p.s. for some reason I can't get preview to work so I hope the code tags take.
Your second problem is that you are trying to access a private variable when you have no access from the function setPlayerName
There are two ways you can fix this, friend the function in your class or get a function in your class to return the variable..
Friend
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#ifndef PLAYER_H
#define PLAYER_H
#include <string>
class Player
{
public:
friendvoid setPlayerName(string); // friend the function so it can access _name
Player();
void playerIntro();
void setPlayerName(std::string inputName);
private:
std::string _name;
};
#endif // PLAYER_H
Just for the sake of my clarity was the problem with my original code for setPlayerName the fact that it was placed in the wrong order, as the function itself seems to be the same as yours for the definition and declaration approach.