2010-10-14 20 views
4

我正在處理一些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 
} 

它不會編譯。我究竟做錯了什麼?

回答

15

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; 
+0

我不知道它是用C寫的,謝謝你告訴我,並給我一個合法的答案! :D – Lemmons 2010-10-14 07:38:02

+1

順便說一下,由於C++ 11的第一個例子可以改寫爲「SDL_Rect location {0,0,600,400};' – HolyBlackCat 2016-02-13 08:56:57

3

作爲替代上面的回答,如果因任何原因,你確實需要動態地創建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;