因此,我对C++不熟悉,而对SDL则是全新的。我对OOP的大部分概念知识都来自Java和PHP。所以,请忍受我。
我正在尝试用我的程序制定一些简单的设计逻辑/即将成为侧滚。我的问题在于试图使我的“屏幕”层(screen = SDL_SetVideoMode(...)
)可供我所有其他类(class)使用;英雄阶层,背景层,敌人等。我一直在松懈地遵循一些程序上的教程,并一直在尝试使它们适应更面向对象的方法。这是我到目前为止的内容:
main.cpp
#include "Game.h"
#include "Hero.h"
int main(int argc, char* argv[])
{
//Init Game
Game Game;
//Load hero
Hero Hero(Game.screen);
//While game is running
while(Game.runningState())
{
//Handle Window and Hero inputs
Game.Input();
Hero.userInput();
//Draw
Game.DrawBackground();
Hero.drawHero();
//Update
Game.Update();
}
//Clean up
Game.Clean();
return 0;
}
如您所见,我有一个Game类和一个Hero类。 Game类负责设置初始窗口并放置背景。如您所见,它还会更新屏幕。
现在,由于我的Game类拥有'screen'属性,它是
SDL_SetVideoMode
的句柄,因此我不得不将其传递给需要更新到此屏幕的任何其他类(ex: Hero Hero(Game.screen);
)...通过SDL_BlitSurface
进行说。现在,这可行了,但是我得到的想法是,GOT是一种更优雅的方法。可能将
screen
处理程序保留在全局范围内(如果可能)?TLDR /简单版本 :使我的所有后续类均可访问我的窗口/屏幕处理程序的最佳方法是什么?
最佳答案
传递Game.screen
比拥有一个可以从任何类访问的实例要更多(尽管拥有getter函数可能更好),因为如果您有一个全局版本,则不能在一个以上拥有一个Game.screen
任何一次。
但是,如果您知道在程序的整个生命周期中只需要一个,则可以考虑将Game::Screen()
设为Game
类中的公共(public)静态函数,该函数返回私有(private)静态成员screen
。这样,任何人都可以调用Game::Screen()
并获取screen
。
示例(假设ScreenType
是screen
的类型,并且您存储了指向它的指针):
class Game {
public:
static ScreenType* Screen() {
if (!screen)
screen = GetScreenType(args);
return screen;
}
}
private:
// if you don't already know:
// static means only one of this variable exists, *not* one per instance
// so there is only one no matter how many instances you make
// the same applies to static functions, which you don't need an instance to call
static ScreenType* screen;
};
// and somewhere in a .cpp file
ScreenType* Game::screen = NULL;
// and you use it like this
ScreenType* scr = Game::Screen();
// use scr