2010-12-01 115 views
0

我的代碼枚舉在C++

void switchstate(gamestates state) --line 53 
{ --line 54 
    switch(state) 
    case state_title: 
     title(); 
     break; 
    case state_about: 
     break; 
    case state_game: 
     break; 
    case state_battle: 
     break; 
} 

enum gamestates 
{ 
state_title, state_about, state_game, state_battle, 
}; 


int main(int argc, char* args[]) 
{ 
gamestates currentstate = state_title; 
startup(); 
load_resources(); 
switchstate(currentstate); --line 169 
return 0; 
} 

,當我嘗試編譯我得到的錯誤:

\ main.cpp中:53:錯誤: 'gamestates' 沒有在這個範圍內聲明
\ main.cpp:54:錯誤:預計','或';'之前 '{' 令牌
\ main.cpp中:在函數 '詮釋SDL_main(INT,字符**)':
\ main.cpp中:169:錯誤: 'switchstate' 不能用作函數

我以前從未使用過枚舉,所以我對什麼不起作用感到困惑。

回答

3

通常,「<symbol>不在範圍內」的錯誤表示編譯器還沒有看到<symbol>。因此,將gamestates的聲明移至void switchstate(...)之前,可以通過之前的#include或將其在文件中向上移動。

C和C++自上而下編譯,因此符號必須在使用前聲明。

2

移動枚舉的聲明,使其位於switchstate函數之上。這應該夠了吧。 C++對聲明的順序非常特別。

0

在switchstate之前將文件中的enum gamestates排隊。

0

嘗試將遊戲狀態的定義移動到switchstate函數定義的上方。

0

您可能想要在switchstate函數之前定義枚舉。

0

在C++中,您必須先聲明所有類型,然後才能引用它們。在這裏,你在switchstate函數之後聲明瞭你的枚舉,所以當C++編譯器讀取switchstate時,它看到你引用了一個它還不知道的類型,並且出錯。如果你在switchstate之前移動枚舉聲明,你應該沒問題。

通常,您應該將聲明放在文件的頂部,或者放在文件頂部包含的單獨頭文件中。