我目前正在尝试用 C++ 制作游戏。在我的代码中,我试图嵌套我的变量,以便我的 main 没有很多包含。不过,我现在的问题是我类(class)中的变量值没有改变。单步执行代码显示它设置了值,但它不起作用。有人知道发生了什么事吗?提前谢谢你。
这是我目前所拥有的:
位置.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
位置.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;}
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
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;}
主要.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;
}
最佳答案
您的直接问题是
Location GetLocation();
返回位置的拷贝,因此当您在此处调用 SetName 时:
playerStats.GetLocation().SetName("Test");
您正在更改临时拷贝的名称,一旦按下分号,更改就会丢失。
更广泛地说,这种设计(嵌套类和嵌套包含使得 main 没有很多包含,并使用 a.b.c() 样式代码访问嵌套成员)不是很好的 C++ 风格:
- 有一堆源文件(传递地)包含一堆头文件意味着更改单个头文件将触发一堆源文件的重新编译。在较大的 C++ 项目中,编译时间可能是一个重要问题,因此通过控制 #include 来减少编译时间很重要。阅读“前向声明”以获取更多信息。
- 编写类似
a.b.c()
的代码被认为是糟糕的面向对象设计,因为它减少了封装:调用者不仅必须了解 a 的详细信息,还必须了解 b 的详细信息。有时这是最方便的代码编写方式,但并不是为了减少#include 而盲目做的事情。阅读“得墨忒耳法则”了解更多信息。
关于c++ - 类中的 setter 不会设置变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27234373/