在我的程序中,我有一个非常简单的结构来表示RPG游戏中的地图。我有一个Map类,它有一个由区域对象组成的2d数组"Grid",如下所示:
#pragma once
#include "Area.h"
class Map
{
public:
Map();
~Map();
Area Grid[10][10];
};然后在Map构造函数中:
Map::Map()
{
for (int y = 0; y < 10; y++) {
for (int x = 0; x < 10; x++) {
Grid[x][y] = Area();
}
}
}我希望Area对象能够访问Map对象中的某些值,并且我已经读过,在构造area对象时,我可以包含对map类的引用,这样它就可以返回到它的父对象。但是要做到这一点,我必须在Area.h中包含"Map.h“,这将创建一个include循环,只是在一般情况下不是很好。那么,我将如何在每个区域对象中注入对区域的父对象的引用呢?谢谢你提前提供帮助。
发布于 2017-11-05 23:22:59
// Area.h
#pragma once
struct Map;
struct Area {
Map* map = nullptr;
Area() {}
explicit Area( Map* m) : map(m) {}
};请注意,您可能希望在Area.cpp (包括Map.h)中定义一些区域的函数。为了示例代码的简单性,我忽略了它。
// Map.h
#pragma once
#include "Area.h"
struct Map
{
Map();
~Map();
Area Grid[10][10];
};
// Map.cpp
#include "Map.h"
Map::Map()
{
for (int y = 0; y < 10; y++) {
for (int x = 0; x < 10; x++) {
Grid[x][y] = Area(this);
}
}
}
Map::~Map() {}
// main.cpp
#include "Map.h"
int main()
{
Map m;
return 0;
}https://stackoverflow.com/questions/47127298
复制相似问题