C++和SDL:SDL_Rect如何工作?
问题描述:
我正在处理一些SDL内容,并且在尝试设置加载的BMP的位置时遇到了一些麻烦。C++和SDL:SDL_Rect如何工作?
这是代码。
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
}
它不会编译。我究竟做错了什么?
答
SDL是用C编写的,因此SDL_Rect
只是一个简单的结构。
要动态地分配它,你不得不使用new
否则编译器会理解你的代码,以所谓的SDL_Rect
普通函数返回一个SDL_Rect*
通话。
在这种情况下,我没有理由使用动态分配;只需使用结构初始化语法(并注意该结构成员的声明顺序):
SDL_Rect location = {0,0,600,400}; // or
SDL_Rect location{0,0,600,400}; // for C++11 & up (h/t @HolyBlackCat)
或明确初始化每个它的成员(更安全的情况下,有人决定重新人气指数结构体的成员的顺序):
SDL_Rect location;
location.h = 600;
location.w = 400;
location.x = 0;
location.y = 0;
答
作为替代上面的回答,如果因任何原因,你确实需要动态地创建location
,你需要做的是这样的:
while(event.type != SDL_QUIT) //The game loop that does everything
{
SDL_Rect *location;
location = new SDL_Rect(600,400,0,0); //add new operator
SDL_PollEvent(&event); //This "polls" the event
//Drawing stuff goes here
SDL_BlitSurface(zombie, NULL, buffer, location);
SDL_Flip(buffer); //Draw
delete location; //IMPORTANT: deallocate memory
}
请注意,因为在循环的每次迭代中都会创建一个额外的SDL_Rect
,并且在下一次迭代中将不再是指向它的指针,所以有必要在循环结束之前将其删除(换句话说,在每次迭代结束之前删除)。否则,你创建一个内存泄漏。
作为另一种替代方案,如果您需要更改为location
以从循环的一次迭代持续到下一次循环,或者如果根本不需要在循环内更改,但是您想清理尾波一点点,你可以做这样的事情:
SDL_Rect *location = new SDL_Rect(600,400,0,0);
while(event.type != SDL_QUIT) //The game loop that does everything
{
SDL_PollEvent(&event); //This "polls" the event
//Drawing stuff goes here
SDL_BlitSurface(zombie, NULL, buffer, location);
SDL_Flip(buffer); //Draw
}
delete location;
我不知道它是用C写的,谢谢你告诉我,并给我一个合法的答案! :D – Lemmons 2010-10-14 07:38:02
顺便说一下,由于C++ 11的第一个例子可以改写为“SDL_Rect location {0,0,600,400};' – HolyBlackCat 2016-02-13 08:56:57