简体   繁体   English

C ++创建一个静态类来存储指针

[英]C++ Create a static class to store pointers

I'm trying to learn my way around C++ by making a simple game/engine with SDL2. 我正在尝试通过使用SDL2创建一个简单的游戏/引擎来学习我的C ++方法。 Currently I'm having some issues trying to make a static class. 目前我在尝试创建静态类时遇到了一些问题。

I think the easiest way is to just describe what I want to achieve: 我认为最简单的方法就是描述我想要实现的目标:

  • I want to be able to make a class (called Pointer) which will store pointers to different crucial objects like the window and the renderer. 我希望能够创建一个类(称为Pointer),它将存储指向不同关键对象(如窗口和渲染器)的指针。
  • I want to set these values to the Pointer class(private variables), from my main *.cpp file after I have created and initialized the window/renderer. 我想在创建并初始化窗口/渲染器之后,从我的main * .cpp文件中将这些值设置为Pointer类(私有变量)。
  • Then I want to be able to use this class to access those objects through getter functions from wherever I might be in the program, but 然后我希望能够使用这个类通过getter函数从程序中的任何地方访问这些对象,但是
  • I want them to be static, so that I can access the original values, and not initialize new empty ones. 我希望它们是静态的,这样我就可以访问原始值,而不是初始化新的空值。

I hope this was somewhat understandable. 我希望这有点可以理解。

( Pointer is a terrible class name.) Pointer是一个可怕的类名。)

You want a class such that only one instance can exist at a time, and it is accessible to any code that is aware of the class. 您需要一个类,以便一次只能存在一个实例,并且任何知道该类的代码都可以访问它。 The solution is the Singleton Pattern . 解决方案是Singleton模式 It is a badly overused pattern (novices like to use it as a substitute for global variables) but this is exactly the kind of thing it's good for. 这是一个严重过度使用的模式(新手喜欢用它作为全局变量的替代品)但这正是它有用的东西。

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

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