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

Posted

技术标签:

【中文标题】C ++使用成员函数返回结构指针属性的值【英文标题】:C++ Use member function to return value of a struct's pointer property 【发布时间】: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-&gt;screenFormat()

非常感谢。

【问题讨论】:

with g_gameSystem-&gt;screenFormat()-&gt;propname(如果我正确理解了您的 Q),但我强烈建议您放弃整个静态恶作剧并使用依赖注入将实例从 main 传递给您的其他函数。跨度> 同样,不相关,但您应该考虑将只读内容设为私有,并提供返回 const 值的访问器。 【参考方案1】:

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

g_gameSystem->screenFormat()->someVariable

另外,一些不请自来的建议,do not use Hungarian notation。

【讨论】:

我不明白为什么代码不能正常工作,因为他的变量的生命周期延伸到 main 的末尾,所以基本上直到程序结束。你的建议只会让它泄漏。 @BartekBanachewicz 你说得对,我删除了堆栈引用的提及。我将其更多地作为警告加入,以避免一般情况下这样做,因为它可能很危险,并且 OP 说他是 C++ 新手,这是一个常见错误。 我试过这个但得到错误““Uint32”类型的参数与“const SDL_PixelFormat *”类型的参数不兼容。我知道这是另一个问题,但我不知道如何解决这个问题要么。 我需要将结果转换为 const SDL_PixelFormat 然后返回吗? @JoshBrown 哦等等我刚刚意识到我的评论(和这个答案)是完全错误的。 screenFormat 已经返回格式。发布您尝试过的实际代码和您遇到的错误。

以上是关于C ++使用成员函数返回结构指针属性的值的主要内容,如果未能解决你的问题,请参考以下文章

C语言结构体中成员若是一个指针时的疑惑??

C++函数指针与成员函数指针

c语言中,函数的形参啥时候必须是指针

尝试使用指向成员函数的指针时出现强制转换问题

this指针 (保存调用成员函数对象的地址)

详解OpenCV的Mat类(构造方法初始化方法常用属性常用成员函数常用操作)