gpt4 book ai didi

c++ - 如何跨文件分配 header

转载 作者:太空宇宙 更新时间:2023-11-04 13:56:08 24 4
gpt4 key购买 nike

编辑澄清:

有没有办法将一个类的 header 拆分到多个文件中,以便其他类可以只包含它应该被允许使用的该类实现的部分?

----下面是我想要的实现的具体细节:---- 不是必读的!

无论如何,我正在创建一个实体组件系统。我想按如下方式构建它:

有一个“EntityPool”对象,主要作为实体及其组件的内存存储/管理器存在。我想从我的“游戏”类中获得指定程度的访问权限(例如,构造/破坏池的能力,以及访问组件数组的能力,以及迭代所有“可渲染”组件的能力)。

有一个“EntityFactory”基类,我希望它能更大程度地访问实体池。它会被“游戏”类使用,如下所示:

GruntEntityFactory ef(&EntityPool); //GruntEntityFactory inherits from EntityFactory 
ef.produce();

然后,实体工厂将使用其对实体池的访问权限来创建必要的组件并将它们放置到位。

这里要注意的是,“游戏”只能创建 EntityPool 并读取其内容,但不能直接更改其内容。另一方面,继承 EntityFactory 的所有内容,我想授予管理 EntityPool 内容的权限。

有没有一种方法可以在每个文件中包含不同的 EntityPool header ,这样每个文件都只“知道”它可以访问的函数?这是执行此操作的最佳方法吗(假设可能)?

此外,我意识到这与 EntityPool 和 EntityFactories 紧密结合。那是故意的。而且,我不想列出我在 EntityPool 中作为友元类创建的每个 EntityFactory。

谢谢!

说明示例代码

//In my Game Class
#include "entitypool.h"
#include "entityfactory_grunt.h"

...

EntityPool ep(); //Construct an EntityPool
GruntEntityFactory gef(&ep); //Pass an EntityPool pointer to an EntityFactory
gef.produce(); //Call produce on GruntEntityFactory, and have it add appropriate components to the EntityPool

//I would like this next line to not be allowed. Game shouldn't be able to
//directly manipulate the components/ other internal EntityPool structure.
//However, I WOULD like EntityFactories to retain the ability to do so.
//(otherwise, how would EntityFactory.produce() work?)
ep.addComponent(PhysicsComponent pc(1, 2, 3));

//I WOULD like Game to be able to access certain functions of EntityPool
for(int i = 0; i < ep.numPhysicsComponents; i++)//Like the count of entities
physicsSolver.update(ep.physicsComponents[i]);//And the ability to update/render components

好的。所以希望这是一个足够明智的例子来了解我想要的东西。标题的原因是我对如何实现这一点的第一直觉是有 2 个头文件。

//EntityPool_GameAccess.h
//This file would contain prototypes for the functions utilized by Game, but NOT the ones
//that game is not allowed to see.

class EntityPool
{
public:
int numPhysicsComponents();
PhysicsComponent getPhysicsComponent(int i);
};

//EntityPool_FactoryAccess.h
//This file would contain prototypes for the functions that only ought be used
//by classes specifically built to manipulate entitypool

class EntityPool
{
public:
void addPhysicsComponent(PhysicsComponent pc);
int numPhysicsComponents();
PhysicsComponent getPhysicsComponent(int i);
};

显然,这些示例都经过了简化。希望我仍然理解这个想法:我想要一个具有特定类可以访问的某些函数以及其他类可以访问其他函数的类。

最佳答案

好的。我终于在 StackOverflow 上的另一个问题中找到了答案:Making classes public to other classes in C++

帕特里克回答的底部:

Unfortunately, there is no way in C++ to make only a part of your class public to a limited set of other classes.

关于c++ - 如何跨文件分配 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21369932/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com