Reputation: 25
I apologize before-hand if this question has been asked before.
I put all my skills with google to use and still nothing so if this question has been answered before please just link the answer and I'll essentially end the question.
Anyway, with all that out of the way, my problem is that I have a class "Player.hpp" and a corresponding "Player.cpp" in which I have defined the location system for the "player" I can initialize the value fine (which is one of the functions of the class) but then when the player goes to the "play()" function (which holds the bones of the game and is located in another .cpp file) when I use the function to get the Location I stored there is nothing stored... any help would be appreciated.
If you don't understand what I'm asking please comment and I'll elaborate.
Code Below:
//Player.hpp
class player
{
public:
std::string getLocation();
void setLocation(std::string local);
void initLocation();
private:
std::string location;
};
//Player.cpp
void player::initLocation()
{
player::location = "B0";
return;
}
std::string player::getLocation()
{
return player::location;
}
void player::setLocation(std::string local)
{
player::location = local;
return;
}
//Main.cpp
//....
player plays;
plays.initLocation();
//....
//Game.cpp
//...
player plays;
std::string local = plays.getLocation(); //When I check there isn't a value that gets stored...
if(local.find(...)...)
Again, any help is appreciated and I apologize if a question like this has already been asked.
I guess I should have clarified that I also want to change the value stored as the player
progresses from room to room (as this is a zork style game I'm making)
Upvotes: 1
Views: 96
Reputation: 70422
Assuming that each instance of player
could be in a separate location, you can resolve this issue by initializing the player
's location with the default location in its constructor. This removes the need for initLocation()
, and thus there is no need to call it from Main.cpp
.
//Player.hpp
class player
{
public:
std::string getLocation();
void setLocation(std::string local);
player () : location("B0") {}
private:
std::string location;
};
Upvotes: 1
Reputation: 153840
It looks as if you omitted static
in front of the class variable declaration:
class player
{
// ...
static std::string location;
};
... which then also requires a definition. Of course, the definition becomes a prime location to also initialize the value:
// Player.cpp
std:string player::location("B0");
making the initialization function unnecessary.
Upvotes: 0