我目前正在研究一个带有SFML的2D游戏引擎,并且从程序上开始,但是决定从长远来看将它转移到OOP会更好。然而,我理解OOP的概念,我并不确定我应该在哪里定义其他类的实例(ImageManager,Grid等)。在哪里实例化依赖于主类的类?
例如,我的Engine
类取决于ImageManager
,许多函数在Engine
依赖于ImageManager
的变量。因此,我不能简单地在单个函数中声明和定义ImageManager
类的实例,因为它在其他函数中不可用。
我做过这样的: Engine.h:
class Engine
{
private:
sf::RenderWindow window;
grid (*gridArray)[SIZE];
...//more variables, removing for length
//Initializes the engine
bool Init(); //Main Game Loop
void MainLoop(); //Renders one frame
void RenderFrame(); //Processes user input
void ProcessInput(); //Updates all Engine internals
public:
Engine(int w, int h, int tileSize);
~Engine();
ImageManager * imageManager;
GridClass * gridClass;
...//removed some methods for length
};
所以基本上,你可以看到我声明了两个班的头,ImageManager
和GridClass
。 Inside Engine.cpp:
Engine::Engine(int w, int h, int tileSize)
{
imageManager = new ImageManager;
gridClass = new GridClass();
gridArray = new grid[SIZE][SIZE]();
masterArray = new unsigned char[MAP_SIZE][MAP_SIZE];
videoSize = sf::Vector2i(w, h);
this->tileSize = tileSize;
startX = startY = endX = endY = 0;
}
我正在定义这些类。我在构造函数中这样做,因为我不确定我应该在哪里做,以符合良好的实践。 我一直有问题imageManager
成为损坏的元素,所以我想知道如果我这样做的方式是一个坏主意或不。
如果这是一个坏主意,你能告诉我应该在哪里实例化这些类吗?请记住,Engine中的许多函数都依赖于这些类的这些实例中的变量,并且我并不想将大量参数传递给每个函数。
谢谢。
我认为你应该使imageManager和gridClass专用,以缩小可以改变它们的范围。你可能想考虑把它们放在一个智能指针中。 – doctorlove