2010-12-01 111 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之前移动枚举声明,你应该没问题。

通常,您应该将声明放在文件的顶部,或者放在文件顶部包含的单独头文件中。