对于一个项目,我正在用 C++ 制作一个简单的基于文本的战斗游戏,我对此并不十分熟悉。
我在将玩家的名字返回到游戏 Controller 时遇到问题。 使用 visual studio 的监视功能,我可以看到在构造时正在设置名称,但是当我尝试在“getName”调用中访问它时,它是空的。这可能与指针有关,但我不确定。
代码和图片如下。
游戏.cpp
#include "Game.h"
Game::Game()
{
Player user = Player("Foo");
gameLoop();
}
void Game::gameLoop()
{
std::string name = user.getName();
printf("name: %s", name.c_str());
}
游戏.h
#include <stdio.h>
#include <string>
#include "Player.h"
class Game
{
public:
Game();
private:
Player user;
void gameLoop();
};
Player.cpp
#include "Player.h"
Player::Player(std::string name)
{
playerName = name;
}
std::string Player::getName() {
std::string nameWatch = playerName;
return playerName;
}
Player.h
#include <stdio.h>
#include <stdlib.h>
#include <string>
class Player
{
public:
Player(std::string name);
Player() {}
std::string getName();
private:
std::string playerName;
};
[ 1
[ 2
最佳答案
在
Game::Game()
{
Player user = Player("Foo");
gameLoop();
}
您创建了一个隐藏this->user
的局部变量user
。
要初始化你的成员变量,你可以这样做
Game::Game() : user("Foo")
{
gameLoop();
}
如果你有几个成员要初始化:
Game::Game() : user("Foo"), comp("Monster")
{
gameLoop();
}
做
Game::Game()
{
user = Player("Foo");
comp = Player("Monster");
gameLoop();
}
创建一个默认的 user
/comp
并为它们分配一个值,因此它要求 Player
是默认可构造的
关于c++ - 访问一个字符串给出空值,即使它被赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33511049/