将枚举传递给另一个文件?C++

P.K*_*.K. 4 c++

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

    enum GameState
    {
        Menu,
        Battle,
        Map,
        SubMenu,
        Typing
    };
Run Code Online (Sandbox Code Playgroud)

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

    GameState State = Menu;
Run Code Online (Sandbox Code Playgroud)

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

    extern GameState State;
Run Code Online (Sandbox Code Playgroud)

但我得到错误

    error: 'GameState' does not name a type
Run Code Online (Sandbox Code Playgroud)

如何将枚举传递给另一个文件?我试图通过将它作为main.cpp中的全局变量,然后将其包含在另一个文件的头中来实现.

Som*_*ude 7

您必须将枚举放在头文件中,并使用#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_
Run Code Online (Sandbox Code Playgroud)

档案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.
Run Code Online (Sandbox Code Playgroud)

档案main.cpp:

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

int main()
{
    if (State == Menu)
        std::cout << "State is Menu\n";
}
Run Code Online (Sandbox Code Playgroud)

现在,全局变量State定义在文件中gamestate.cpp,但可以在包括所有的源文件引用gamestate.h感谢extern在该文件中声明.更重要的是,GameState当您gamestate.h在源文件中包含时,也会定义枚举类型,以便您没有定义的错误将消失.

有关声明和定义之间的区别,请参阅/sf/answers/98744271/.