数组分配
Array Allocation
我有一个名为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
调用的结果分配给它来消除该指针。现在,您将永远无法delete
曲面,因为您丢失了指向它的指示器。您可以考虑封装您的sprite并使用RAII习惯用法来处理SDL_Surface
的分配。
除此之外,最好使用std::vector
而不是数组。
SDL_Surface getSprite(int sprite_index)
应为:
SDL_Surface* getSprite(int sprite_index)
相关文章:
- 将数组的地址分配给变量并删除
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- 获取字符串的长度并将其分配给数组
- 在c++中为我自己的基于指针的数组分配内存的正确方法
- 使用递归模板动态分配的多维数组
- 如何正确填充在堆上分配的二维数组?
- 在函数范围内在堆栈上分配的数组在离开函数时是否总是被释放?
- 在 C++ 中搜索动态分配的数组中的出现次数
- 动态分配的聊天数组打印缺失的数据和空
- 关于字符数组,我正在尝试将数组中的每个字符分配给另一个值
- 我似乎无法为指针分配一个数组,然后更改数组的内容
- 具有自定义构造函数 (C++) 的类型的动态数组分配
- 无法分配C++数组
- 如何增加以前由新运算符分配的 C++ std::list 数组的大小?
- 分配 2D 可变大小的数组
- 介于 [固定数组] 和 [带内存分配的指针] 之间的性能
- 动态分配字符数组的内存
- C++具有动态分配的字符数组的结构
- C 通过参考分配 /数组传递内存
- 使用字符串或字符动态分配(数组)