【问题标题】:Global enum in C++C++ 中的全局枚举
【发布时间】:2014-07-17 21:20:52
【问题描述】:

好吧,我想将地形枚举定义为

enum terrain {MOUNTAIN, GRASS};

什么的。

如何使这个枚举成为项目中所有类中定义的东西?

【问题讨论】:

  • 把它放在你包含的头文件中。
  • 假设我希望在多个类中定义枚举,我是否必须为每个类重新定义它?
  • 对于 C++11 更喜欢 class enums 而不是“普通”enums
  • @Alper: enum class 会更好。

标签: c++ enums


【解决方案1】:

将您的enum 声明放在头文件中:

地形.h

#ifndef TERRAIN_H
#define TERRAIN_H

enum terrain {MOUNTAIN, GRASS};

#endif

#ifndef/#define 对是 include 保护,您可以在其他地方阅读这些内容。)

source.cpp

#include <stdio.h>
#include "terrain.h"

// your code here

在您需要的每个源文件中包含terrain.h 文件。如果需要,您还可以包含另一个头文件中的头。

【讨论】:

  • "You can also include a header from another header file if you need to." OP,请非常谨慎地接受这个建议。强调“如果您需要”。避免在不必要时在标题中包含标题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-26
  • 1970-01-01
  • 2015-07-06
  • 1970-01-01
  • 2011-02-20
相关资源
最近更新 更多