如何获得对不同类的引用,以便从所述类内部获得变量值

How to get a reference to a different class in order to get a variable value from inside said class?

本文关键字:内部 变量值 何获得 同类 引用      更新时间:2023-10-16

我有一个称为MapGraph的类和另一个名为GameState的类。我从main调用两个函数GoToLocation(NextLocation);Game->SidePanel();。GoToLocation((声明和定义分别存在于MapGraph.hMapGraph.cpp中,SidePanel((声明与定义分别存在于GameState.hGameState.cpp中。在SidePanel((中,我试图获取一个名为CurrentLocation的变量的值,该变量存在于MapGraph中并且是公共的。我已经在GameState.cpp中包含了MapGraph.h,并将类声明为class MapGraph;,但我不知道如何获得变量的值。如果我执行MapGraph* Map = new MapGraph;,它总是给我变量的初始值,而不是更新后的值。如有任何帮助,我们将不胜感激。非常感谢。

main.cpp:中的代码

int main()
{
MapGraph* Map = new MapGraph;
GameState* Game = new GameState;
//Game->MainMenu();
Map->GoToLocation(MapGraph::LocationNames::CastleSquare);
Game->SidePanel();
//system("CLS");
return 0;
}

MapGraph.h

#pragma once
#include <iostream>
#include <list>
#include <string.h>
class MapGraph
{
public:
MapGraph();
enum class LocationNames
{
GraveYard = 0,
Sewers = 1,
Outskirts = 2,
Barracks = 3,
Town = 4,
CastleSquare = 5,
ThroneRoom = 6,
Forest = 7,
Gutter = 8,
HunterShack = 9
};
std::string LocNamesString[10] =
{
"Grave Yard",
"Sewers",
"Outskirts",
"Barracks",
"Town",
"Castle Square",
"Throne Room",
"Forest",
"Gutter",
"Hunter Shack"
};
LocationNames CurrentLocation;
void GoToLocation(LocationNames NextLocation);
};

GameState.cpp

#include <iostream>
#include <stdlib.h>
#include "GameState.h"
#include "MapGraph.h"
class MapGraph;
void GameState::SidePanel()
{
MapGraph* Map = new MapGraph;
std::cout << Map->LocNamesString[(int)Map->CurrentLocation];
}

附言:我尝试将MapGraph.h中的CurrentLocation更改为static,但这总是会生成链接器错误2001。一旦我删除单词static,错误就会消失。

谢谢

有几种方法可以设计这种关系。由你来决定哪一个最适合你的整体设计。(一个大问题是,你希望同时存在多少个MapGraph对象?(最简单的方法可能是将所需的变量作为参数传递。

void GameState::SidePanel(cosnt MapGraph & Map)
{
std::cout << Map.LocNamesString[(int)Map.CurrentLocation];
}

尽管如此,我还是会更进一步,将这一行逻辑合并到MapGraph类中。在这种情况下,您的功能将变为

void GameState::SidePanel(cosnt MapGraph & Map)
{
std::cout << Map.CurrentLocationName();
}

并将以下内容添加到CCD_ 19定义中

class MapGraph {
// Existing stuff here
public:
std::string CurrentLocationName()
{
return LocNamesString[(int)CurrentLocation];
}
// Possibly more definitions here
};

一般来说,只有MapGraph实现才需要知道MapGraph数据是如何存储的。当其他代码需要MapGraph数据的组合时(例如将当前位置转换为字符串(,MapGraph类应该提供一个接口。

顺便说一下,LocNamesString可能是staticconststatic关键字表示名称字符串在MapGraph对象和MapGraph对象之间没有变化。const关键字表示初始化后名称字符串不会更改