【发布时间】:2017-04-24 20:00:18
【问题描述】:
我正在使用 SDL 学习一些 C++,但遇到了一个令人困惑的问题。
我在头文件中有一个类:
SDL_Surface* loadImage(const char*);
class GameSystem
{
public:
// Constructor
GameSystem();
// Destructor
~GameSystem();
SDL_PixelFormat* screenFormat();
private:
SDL_Window* m_window;
SDL_Surface* m_screen;
}
// Global pointer for all to access
extern const GameSystem* g_gameSystem;
在构造函数中,m_window 和 m_screen 被初始化。在各自的源文件中,我定义了这个成员函数:
SDL_PixelFormat* GameSystem::screenFormat()
{
return m_screen->format;
}
m_screen的结构是这样的:
typedef struct SDL_Surface
{
Uint32 flags; /**< Read-only */
SDL_PixelFormat *format; /**< Read-only */
int w, h; /**< Read-only */
int pitch; /**< Read-only */
void *pixels;
}
要运行它,在main() 函数中,我得到一个GameSystem 实例,然后将g_gameSystem 从头文件指向该实例。像这样:
int main(int argc, char** argv)
{
// Initialise the game system core
GameSystem gameSystem;
// Make the global gameSystem pointer point to this instance
g_gameSystem = &gameSystem;
我的问题是:如何获取 format 属性的值以使用 screenFormat 函数,如下所示:g_gameSystem->screenFormat()
非常感谢。
【问题讨论】:
-
with
g_gameSystem->screenFormat()->propname(如果我正确理解了您的 Q),但我强烈建议您放弃整个静态恶作剧并使用依赖注入将实例从main传递给您的其他函数。跨度> -
同样,不相关,但您应该考虑将只读内容设为私有,并提供返回
const值的访问器。
标签: c++ oop pointers struct sdl