【问题标题】:Enumerations in C++C++ 中的枚举
【发布时间】:2010-12-01 23:12:26
【问题描述】:

我有密码

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:在函数“int SDL_main(int, char**)”中:
\main.cpp:169: 错误:'switchstate' 不能用作函数

我以前从未使用过枚举,所以我对什么不起作用感到困惑。

【问题讨论】:

    标签: c++ enums compiler-errors enumeration


    【解决方案1】:

    一般来说,“<symbol>不在范围内”的错误意味着编译器还没有看到<symbol>。所以将gamestates 的声明移动到void switchstate(...) 之前,或者通过更早的#include 或者只是在文件中向上移动它。

    C 和 C++ 是从上到下编译的,所以符号必须在使用前声明。

    【讨论】:

      【解决方案2】:

      移动枚举的声明,使其位于switchstate 函数的上方。这应该够了吧。 C++ 对事物的声明顺序非常讲究。

      【讨论】:

        【解决方案3】:

        将文件中的enum gamestates 行移到switchstate 之前。

        【讨论】:

          【解决方案4】:

          您可能希望在 switchstate 函数之前定义枚举。

          【讨论】:

            【解决方案5】:

            在 C++ 中,您必须先声明所有类型,然后才能引用它们。在这里,你在 switchstate 函数之后声明你的枚举,所以当 C++ 编译器读取 switchstate 时,它​​会看到你引用了一个它还不知道的类型,并且会出错。如果你在 switchstate 之前移动枚举声明,你应该没问题。

            一般来说,您应该将声明放在文件顶部,或者放在文件顶部包含的单独头文件中。

            【讨论】:

              【解决方案6】:

              尝试将游戏状态的定义移到 switchstate 函数定义之上。

              【讨论】:

                猜你喜欢
                • 2010-11-26
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2016-07-10
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多