gpt4 book ai didi

c++ - SDL_RenderCopy() 意外行为

转载 作者:行者123 更新时间:2023-12-02 09:54:37 24 4
gpt4 key购买 nike

我很确定这一点也不意外,我可能误解了一些东西。我正在尝试调用其中一个重载的构造函数:
SDL_RenderCopy(SDL_Renderer*, SDL_Texture*, SDL_Rect*, SDL_Rect*);
当我在一个类中创建一个静态方法来检索 SDL_Rect 指针时,问题就来了:

static SDL_Rect* getRectangle(rect r) {
SDL_Rect rectangle{ r.x, r.y, r.w, r.h };
return &rectangle;
}

所以调用是这样的:
SDL_Rect* r = MyClass::getRectangle(srcRect);
SDL_Rect* r2 = MyClass::getRectangle(destRect);
SDL_RenderCopy(renderer, texture, r, r2);

它们都是指针并返回一致的值,但由于某种原因,我不明白,当传递给 SDL 时,我从类中获取的矩形没有根据矩形的值进行缩放。但是如果我更改我的静态方法以返回 SDL_Rect 的拷贝,一切都按预期工作,例如:
static SDL_Rect getRectangle(rect r) {
SDL_Rect rectangle{ r.x, r.y, r.w, r.h };
return rectangle;
}

和电话:
SDL_Rect r = Video::getRectangle(srcRect);
SDL_Rect r2 = Video::getRectangle(destRect);
SDL_RenderCopy(renderer, texture, &r, &r2);

最佳答案

问题出在您的函数中 getRectangle() :

static SDL_Rect* getRectangle(rect r) {
SDL_Rect rectangle{ r.x, r.y, r.w, r.h };
return &rectangle;
}

您正在返回一个对象的地址, rectangle ,具有自动存储期限。因此,控件从函数返回后,该对象就不存在了。

您可能想要分配一个 SDL_Rect在堆上并返回其地址:
static SDL_Rect* getRectangle(rect r) {
return new SDL_Rect{ r.x, r.y, r.w, r.h };
}

关于c++ - SDL_RenderCopy() 意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61252914/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com