【问题标题】:how to manage multiple files, global variables, and defines如何管理多个文件、全局变量和定义
【发布时间】:2012-11-10 11:31:13
【问题描述】:

我有两个类,“实体”类和“瓦片”类。

类“entity”有一些成员函数使用“tile”类型的全局数组。它还使用一些定义的数字。

类“tile”包含一个成员变量,它是指向类型“entity”的指针。

我想将这些类分成不同的 .h 文件。我将尝试对其进行重组,但我确实想知道是否可以这样做。

所以,再次为清楚起见:

“entity”使用“tile”类型的全局二维数组

“平铺”使用

有什么方法可以将其拆分为三个 .h 文件(每个类一个,一个用于所有全局变量和定义)?

谢谢!

【问题讨论】:

  • 重新设计这样你就不需要全局变量了吗?

标签: c++ class header include


【解决方案1】:

我不明白你为什么需要三个 .h 文件。只需为每个类创建一个单元,然后将全局放入 Entity 的模块中(我不认为您可以避免使用全局)。

Entity.h

class Entity
{
<...>
};

Entity.cpp

#include "Entity.h"
#include "Tile.h"

Tile array[100];//here's your array

Tile.h

#include "Entity.h"

class Tile
{
    <...>
    Entity * ptr;//here's your pointer
};

【讨论】:

  • 我试过这个并且它有效,但我似乎无法访问主函数中的数组。我怎么能那样做?这是一种很好的替代方法,但为了将所有全局变量放在一个位置,是否可以有一个单独的文件(如 global.h)而不是将全局变量放在实体模块中?
  • @Nathan,你不应该那样做(就是把数组放到 .h 中)。要从另一个模块(即您的主模块)访问数组,您应该使用 extern 关键字:extern Tile array[100]
  • 谢谢!它编译干净。
【解决方案2】:

我认为您只需要对 Entity 类进行前向声明吗?

tile.h:

class Entity;

class Tile {
     Entity *entity;
      ...
}

实体.h:

//#include "tile.h" - add this back if you need to refer to tile in Entity defn

class Entity {
    ...
}

实体.cpp

#include "entity.h"
// Remove the following or put in proper include protection if you uncomment the 
// include above
#include "tile.h"

Tile gbl[10][10];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-20
    相关资源
    最近更新 更多