我有一个名为 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_Surface
和 SDL_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_Surface
的 getSprite
函数中,您试图返回一个 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/