c++ - 数组分配

标签 c++ sdl

我有一个名为 SpriteCollection 的类,我在其中使用 SDL 加载图像。这个类有一个属性叫做:

SDL_Surface* sprites[];

我认为这是正确的(尽管我不确定)。在同一个类中,我有一个方法:

void addNewSprite(SDL_Surface* sprite){

    this->sprites[n_sprites+1] = new SDL_Surface;
    this->sprites[n_sprites+1] = IMG_Load("spritepath.jpg");
    this->n_sprites++;
}

另一个检索 SDL_Surface 以在屏幕上绘制:

SDL_Surface getSprite(int sprite_index){

    return this->sprites[sprite_index];
}

然后在我正在使用的屏幕上绘图:

Draw(x_position, y_position, this->sprite->getSprite[0], screen);

我正在正常加载图像;一切正常,但 IDE 返回有关指针和 SDL_SurfaceSDL_Surface * 之间转换的错误。

我做错了什么?

编辑:错误信息:

E:\cGame.cpp|71|error: cannot convert `SDL_Surface' to `SDL_Surface*' for argument `1' to `int SDL_UpperBlit(SDL_Surface*, SDL_Rect*, SDL_Surface*, SDL_Rect*)'|

最佳答案

在返回类型为 SDL_SurfacegetSprite 函数中,您试图返回一个 SDL_Surface*。也许你的意思是:

SDL_Surface* getSprite(int sprite_index){
  return this->sprites[sprite_index];
}

此外,这些行很可疑:

this->sprites[n_sprites+1] = new SDL_Surface;
this->sprites[n_sprites+1] = IMG_Load("spritepath.jpg");

首先,您要动态分配一个新的 SDL_Surface 并存储指向它的指针。然后,您通过将 IMG_Load 调用的结果分配给它来摆脱该指针。现在您将永远无法删除 表面,因为您已经丢失了指向它的指针。您可能会考虑封装您的 Sprite 并使用 RAII处理 SDL_Surface 分配的习惯用法。

最重要的是,您最好使用 std::vector 而不是数组。

关于c++ - 数组分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9759730/

相关文章:

c++ - SDL_main 与 VS2010 的链接问题

c++ - valgrind:opencv 中的 cvCvtColor 错误

调用析构函数后的 C++ 动态模板队列 "double free or corruption (out)"

c++ - Xcode 中缺少 C++ 命令行工具应用程序的 info.plist 文件

haskell - 尝试安装 cabal 包 sdl-mpeg 找不到包含文件 smpeg.h

video - 在 Windows 7 上使用 MinGW 构建具有视频支持的 PJSIP

c++ - 在公共(public)目标文件中分隔调用者

c++ - 我如何优化/改进这个哈希函数

c++ - SDL_Jostick 正在发送奇怪的整数

c++ - SDL 和 Visual Studio 2010 资源