C++ 使用成员函数返回结构体指针属性的值

C++ Use member function to return value of a struct's pointer property

本文关键字:指针 属性 结构体 返回 成员 函数 C++      更新时间:2023-10-16

我正在用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()函数中,我获得了游戏系统的实例,然后从header文件到该实例。喜欢:

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()

非常感谢。

回答您的实际问题,因为我假设m_screen在您的构造函数中适当初始化:

g_gameSystem->screenFormat()->someVariable

另外,一些未经请求的建议,请勿使用匈牙利符号。