数组分配

Array Allocation

本文关键字:分配 数组      更新时间:2023-10-16

我有一个名为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调用的结果分配给它来消除该指针。现在,您将永远无法delete曲面,因为您丢失了指向它的指示器。您可以考虑封装您的sprite并使用RAII习惯用法来处理SDL_Surface的分配。

除此之外,最好使用std::vector而不是数组。

SDL_Surface getSprite(int sprite_index)

应为:

SDL_Surface* getSprite(int sprite_index)