类中的setter不会设置变量

Why*_*ork 0 c++ getter-setter

我目前正在尝试用C++制作游戏.在我的代码中,我试图嵌套我的变量,以便我的主要没有很多包含.我现在的问题是我班上变量的值没有变化.单步执行代码会显示它设置值,但它不起作用.有谁知道发生了什么?先感谢您.

这是我到目前为止:

Location.h

#ifndef LOCATION_H
#define LOCATION_H

#include <string>

class Location
{
public:
    Location(void);
    Location(std::string name);
    ~Location(void);

    std::string GetName();
    void SetName(std::string value);

private:
    std::string m_Name
};

#endif
Run Code Online (Sandbox Code Playgroud)

Location.cpp

#include "Location.h"

Location::Location(void): m_Name("") {}

Location::Location(std::string name): m_Name(name) {}

Location::~Location(void)
{
}

std::string Location::GetName()
{return m_Name;}

void Location::SetName(std::string value){m_Name = value;}
Run Code Online (Sandbox Code Playgroud)

PlayerStats.h

#ifndef PLAYERSTATS_H
#define PLAYERSTATS_H

#include "Location.h"

class PlayerStats
{
public:
    PlayerStats(void);
    ~PlayerStats(void);

    Location GetLocation();
    void SetLocation(Location location);

private:
    Location m_Location;
};

#endif
Run Code Online (Sandbox Code Playgroud)

PlayerStats.cpp

#include "PlayerStats.h"

PlayerStats::PlayerStats(void): m_Location(Location()) {}

PlayerStats::~PlayerStats(void)
{
}

Location PlayerStats::GetLocation(){return m_Location;}

void PlayerStats::SetLocation(Location location){m_Location = location;}
Run Code Online (Sandbox Code Playgroud)

main.cpp中

#include <iostream>
#include "PlayerStats.h"

using namespace std;

PlayerStats playerStats = PlayerStats();

int main()
{
    playerStats.GetLocation().SetName("Test");
    cout<< playerStats.GetLocation().GetName()<<endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Jos*_*ley 5

你的直接问题是

Location GetLocation();
Run Code Online (Sandbox Code Playgroud)

返回该位置的副本,因此在此处调用SetName时:

playerStats.GetLocation().SetName("Test");
Run Code Online (Sandbox Code Playgroud)

您正在更改临时副本的名称,一旦分号被击中,更改就会丢失.

更广泛地说,这种设计(嵌套类和嵌套包括主要没有很多包含,并使用abc()样式代码来访问嵌套成员)并不是很好的C++风格:

  • 拥有一堆(传递)包含一堆头文件的源文件意味着更改单个头文件将触发一堆源文件的重新编译.在较大的C++项目中,编译时间可能是一个重要问题,因此通过控制#include来减少编译时间非常重要.阅读"前向声明"以获取更多信息.
  • 编写类似的代码a.b.c()被认为是不好的面向对象设计,因为它减少了封装:不仅调用者必须知道一个细节,它还必须知道b.有时候这是编写代码最方便的方法,但是为了减少#include而不是盲目地做.阅读"Demeter法则"以获取更多信息.