gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:24:30 25 4
gpt4 key购买 nike

第一次在这里发帖,我是 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 中的全局变量然后将其包含在另一个文件的 header 中来实现。

最佳答案

您必须将枚举放在头文件中,并使用#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.h 感谢该文件中的 extern 声明。更重要的是,当您将 gamestate.h 包含在源文件中时,枚举类型 GameState 也会被定义,因此关于它未被定义的错误将会消失。

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

关于c++ - 将枚举传递给另一个文件? C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11969762/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com