5

第一次在这里发帖,我是 C++ 编程的初学者,学习它主要是因为我想知道它,因为它总是很有趣,因为它是如何工作的等等。
我正在尝试使用 SFML 2.0 制作一个简单的游戏,我的问题是:
我有一个枚举,例如:

    enum GameState
    {
        Menu,
        Battle,
        Map,
        SubMenu,
        Typing
    };

所以,我想制作一个这样的变量,使用

    GameState State = Menu;

然后,将其传递给另一个文件

    extern GameState State;

但我得到错误

    error: 'GameState' does not name a type

如何将枚举传递给另一个文件?我试图通过将其作为 main.cpp 中的全局变量,然后将其包含在另一个文件的标题中来做到这一点。

4

2 回答 2

9

您必须将枚举放在头文件中,并用于#include将其包含在源文件中。

像这样的东西:

文件gamestate.h

// These two lines prevents the file from being included multiple
// times in the same source file
#ifndef GAMESTATE_H_
#define GAMESTATE_H_

enum GameState
{
    Menu,
    Battle,
    Map,
    SubMenu,
    Typing
};

// Declare (which is different from defining) a global variable, to be
// visible by all who include this file.
// The actual definition of the variable is in the gamestate.cpp file.
extern GameState State;

#endif // GAMESTATE_H_

文件gamestate.cpp

#include "gamestate.h"

// Define (which is different from declaring) a global variable.
GameState State = Menu;  // State is `Menu` when program is started

// Other variables and functions etc.

文件main.cpp

#include <iostream>
#include "gamestate.h"

int main()
{
    if (State == Menu)
        std::cout << "State is Menu\n";
}

现在全局变量在文件State定义,但由于该文件中的声明,gamestate.cpp可以在包含的所有源文件中引用。更重要的是,当您包含在源文件中时,也会定义枚举类型,因此您对它未定义的错误将消失。gamestate.hexternGameStategamestate.h

有关声明和定义之间的区别,请参见例如https://stackoverflow.com/a/1410632/440558

于 2012-08-15T13:07:41.800 回答
1

问题似乎是您已经在一个文件中定义了 GameState 的含义,但是 2 个文件需要知道定义。完成此操作的典型方法是创建一个头文件(扩展名为 .h),该头文件(使用#include)包含在两个源代码文件(最有可能是 .cpp)中,以便它出现在两个源代码文件中。这比仅复制和粘贴定义要好(要在其他地方使用它,您只需要 #include 语句;如果定义发生更改,您只需在 .h 文件中更改它,并且包含它的每个文件在重新编译时都会得到更改) .

于 2012-08-15T13:08:15.713 回答