如何获得对不同类的引用,以便从所述类内部获得变量值
How to get a reference to a different class in order to get a variable value from inside said class?
我有一个称为MapGraph
的类和另一个名为GameState
的类。我从main
调用两个函数GoToLocation(NextLocation);
和Game->SidePanel();
。GoToLocation((声明和定义分别存在于MapGraph.h
和MapGraph.cpp
中,SidePanel((声明与定义分别存在于GameState.h
和GameState.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
可能是static
和const
。static
关键字表示名称字符串在MapGraph
对象和MapGraph
对象之间没有变化。const
关键字表示初始化后名称字符串不会更改
- 使用变量值作为 PlaySound 中的路径
- 通过指针偏移量访问结构变量值
- 变量值在 C++ 中的 glutIdleFunc() 中未递增
- 更新 #ifdef 中的现有变量值?
- 尝试更改 main 函数内的全局变量值时出现编译错误 C++.
- 通过 Rcpp 和 bit64 R 包将最大的int64_t变量值从 C++ 传递到 R
- 如何使用 IRBuilder 更新 LLVM IR 中的全局变量值?
- 更改已在运行的程序的变量值
- 在 Xcode 中使用后对外部变量值进行初始化
- C++整数变量值
- 变量值,在三元运算符之后
- 如何获得对不同类的引用,以便从所述类内部获得变量值
- Java应用程序的JNI-c++变量值
- 如何固定从传感器获得的变量值
- 离开方法时重置变量值
- 打印具有通用特定变量值的类对象
- 在宏函数C++中设置宏变量值
- 为什么每次迭代都会获得相同的变量值? C++
- 如何根据基类对象中的变量值分配派生类中的变量?
- 如何将全局字符变量值分配给数组?