C++和 SDL:SDL_Rect 到底是如何工作的?
我正在研究一些 SDL 的东西,并且在尝试设置加载的 BMP 的位置时遇到了一些麻烦。
这是代码。
while(event.type != SDL_QUIT) //The game loop that does everything
{
SDL_Rect *location;
location = SDL_Rect(600,400,0,0);
SDL_PollEvent(&event); //This "polls" the event
//Drawing stuff goes here
SDL_BlitSurface(zombie, NULL, buffer, &location);
SDL_Flip(buffer); //Draw
}
它不会编译。我做错了什么?
I'm working on some SDL stuff and I've run into some trouble when trying to set the location of a loaded BMP.
Here's the code.
while(event.type != SDL_QUIT) //The game loop that does everything
{
SDL_Rect *location;
location = SDL_Rect(600,400,0,0);
SDL_PollEvent(&event); //This "polls" the event
//Drawing stuff goes here
SDL_BlitSurface(zombie, NULL, buffer, &location);
SDL_Flip(buffer); //Draw
}
It won't compile. What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
SDL 是用 C 编写的,因此
SDL_Rect
只是一个简单的结构。要动态分配它,您必须使用
new
否则编译器会将您的代码解释为对名为SDL_Rect
的常规函数的调用,该函数返回SDL_Rect*< /代码>。
在这种情况下,我认为没有理由使用动态分配;只需使用结构体初始化语法(并注意结构体成员的声明顺序):
或显式初始化它的每个成员(如果有人决定重新排列结构体成员的顺序,则更安全):
SDL is written in C so
SDL_Rect
is just a simple struct.To dynamically allocate it you'd have to use
new
otherwise the compiler will interpret your code as a call to a regular function calledSDL_Rect
that returns aSDL_Rect*
.In this case I see no reason to use dynamical allocation; just use the struct initialization syntax (and be careful of the declaration order of the struct's members):
or explicitly initialize each of it's members (safer in case somebody decides to re-arange the order of the struct's members):
作为上述答案的替代方案,如果出于任何原因,您确实需要动态创建
location
,则需要这样做:请注意,因为额外的
SDL_Rect 会在循环的每次迭代中创建,并且在下一次迭代时将不再有指向它的指针,需要在循环结束之前删除它(换句话说,在循环结束之前删除它)每次迭代)。否则,就会造成内存泄漏。
作为另一种选择,如果您需要对
location
进行更改以从循环的一次迭代持续到下一次迭代,或者如果您根本不需要在循环内进行更改,但您想要清理稍微提高你的尾声,你可以这样做:As an alternative to the above answer, if, for any reason, you did need to dynamically create
location
, you would need to do it like this:Note that, because an additional
SDL_Rect
will be created on each iteration of the loop, and there will cease to be a pointer to it on the next iteration, it is necessary to delete it before the end of the loop (in other words, to delete before the end of each iteration). Otherwise, you create a memory leak.As an additional alternative, if you needed changes to
location
to persist from one iteration of your loop to the next, or if you didn't need to change within the loop at all, but you wanted to clean up your coda a little, you could do something like this: