即使分配了字符串,访问字符串也会给出空值

时间:2015-11-03 23:27:46

标签: c++ string pointers std

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

我在将玩家的名字输入游戏控制器时遇到问题。 使用visual studio的watch功能,我可以看到在构造时正在设置名称,但是当我尝试使用' 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;
};

[Name is set to playerName 1

[Player name is now empty? 2

2 个答案:

答案 0 :(得分:3)

Game::Game() 
{
    Player user = Player("Foo");
    gameLoop();
}

您创建一个隐藏user的本地变量this->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是默认可构造的

答案 1 :(得分:1)

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