简体   繁体   English

通过组合访问父类

[英]Accessing parent classes through composition

In my program i have a very simple structure to represent a map in an RPG game. 在我的程序中,我有一个非常简单的结构来表示RPG游戏中的地图。 I have a Map class, with a 2d Array, "Grid", made out of Area objects, like so: 我有一个Map类,其中包含一个由Area对象组成的2d数组“ Grid”,如下所示:

 #pragma once
 #include "Area.h"

 class Map
 {
 public:
     Map();
     ~Map();

     Area Grid[10][10];
 };

Then in the Map constructor: 然后在Map构造函数中:

 Map::Map()
 {
for (int y = 0; y < 10; y++) {
    for (int x = 0; x < 10; x++) {
        Grid[x][y] = Area();
    }
}
}

I would like for the Area objects to be able to access certain values from the Map object, and I've read that i could include a reference to the map class when constructing the area object, so that it can refer back to its parent. 我希望Area对象能够从Map对象访问某些值,并且我读到,在构造Area对象时,我可以包括对map类的引用,以便它可以返回其父对象。 But to do this, i would have to #include "Map.h" in Area.h, which would create an include loop, and just not be very good in general. 但是要做到这一点,我将不得不在Area.h中#include“ Map.h”,这将创建一个include循环,并且总体上不是很好。 So how would i go about injecting a reference to the area's parent in each area object? 那么我将如何在每个区域对象中注入对该区域父对象的引用? Thanks for any help in advance. 感谢您的任何帮助。

// Area.h
#pragma once
struct Map;

struct Area {
    Map* map = nullptr;
    Area() {}
    explicit Area( Map* m) : map(m) {}
};

Note that you may want to have some of the functions of Area defined in Area.cpp (that includes Map.h). 请注意,您可能想拥有Area.cpp(包括Map.h)中定义的Area的某些功能。 I just left it out for simplicity of example code. 为了示例代码的简单起见,我只是省略了它。

// 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM