c++ - 访问一个字符串给出空值,即使它被赋值

标签 c++ string pointers std

对于一个项目,我正在用 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;
};

[ Name is set to playerName 1

[ Player name is now empty? 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/

相关文章:

c# - 如何检查两个字符串是否在 C# 中部分匹配?

Python/Pandas 将字段字符串解包为多个字段

C++ 指针在函数调用后在继承中失去值(value)。

c# - 无法分配静态双指针变量

c++ - 使用 Qt 组件编译 C++ 代码

c++ - 将 CERTCertificate derCert 转换为 SECKEYPublicKey

Java/RegEx - 模式否定不起作用

pointers - 防止 F# 中的垃圾收集器移动对象

c++ - MakeFile 中的 "undefined reference to"

c++ - C++ 中的 exit 和 std::exit 有什么区别?