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

Accessing a string gives empty value even though it is assigned

对于一个项目,我正在用 C++ 制作一个简单的基于文本的战斗游戏,我对此并不十分熟悉。

我在将玩家的名字返回到游戏控制器时遇到问题。 使用 visual studio 的监视功能,我可以看到在构造时正在设置名称,但是当我尝试在 'getName' 调用中访问它时,它是空的。这可能与指针有关,但我不确定。

下面的代码和图片。

Game.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());
}

Game.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 是默认可构造的

Game::Game()
{
    Player user = Player("Foo"); 
    // you create local object with name user that override class-member object 
    // with same name. At least, you have user object like class member is empty cause
    // constr initialization-list is empty, and compiler call default const for std::string class that
    // exactly empty string, and local Player object with name user that die on close brace end.

    // First of all, use "Hungarian notation" style to detect class-member variables, for example:
    // 
    // class Hello
    // {
    //  private:
    //    int m_user;
    // }


    // At second, if one of your class-members haven't default constr and you should explicit call correct 
    // constructor use "Constructor initialization-list, like
    //
    // Game::Game() :
    //  m_user("Mike")
    // {
    //
    // }

    gameLoop();
}