English 中文(简体)
C++定义跨文件常量的最佳方法
原标题:
  • 时间:2009-03-13 03:45:27
  •  标签:

我正在制作一个游戏,有一个有趣的问题。我有一些游戏范围的常量值,希望在一个文件中实现。目前我有类似这样的东西:

常量.cpp

extern const int BEGINNING_HEALTH = 10;
extern const int BEGINNING_MANA = 5;

常数.hpp

extern const int BEGINNING_HEALTH;
extern const int BEGINNING_MANA;

And then files just #include "常数.hpp" This was working great, until I needed to use one of the constants as a template parameter, because externally-linked constants are not valid template parameters. So my question is, what is the best way to implement these constants? I am afraid that simply putting the constants in a header file will cause them to be defined in each translation unit. And I don t want to use macros.

谢谢 (xiè xiè)

最佳回答

去掉extern,你就设置好了。

这段代码在头文件中完全正常工作,因为所有内容都是“真正的常量”,因此具有内部链接:

const int BEGINNING_HEALTH = 10;
const int BEGINNING_MANA = 5;
const char BEGINNING_NAME[] = "Fred";
const char *const BEGINNING_NAME2 = "Barney";

该代码不能安全地放在头文件中,因为每行都具有外部链接(要么明确,要么因未真正是常量而如此)。

extern const int BEGINNING_HEALTH = 10;
extern const int BEGINNING_MANA = 5;
const char *BEGINNING_NAME = "Wilma";  // the characters are const, but the pointer isn t
问题回答

枚举如何?

常量.hpp

  enum {
    BEGINNING_HEALTH = 10,
    BEGINNING_MANA = 5
  }

在你的.hpp文件中使用“static const int”,在.cpp文件中什么也不要放(当然,除了其他代码)。

利用命名空间:

namespace GameBeginning {
    const int HEALTH = 10;
    const int MANA   = 5; 
};

那么您可以使用 player.health = GameBeginning::HEALTH;

大多数编译器都不会为const POD值分配空间。它们会将它们优化并将它们视为已经被#define。不是吗?

“不知道发生了什么事,为什么不再像以前那么简单了呢?”

#define BEGINNING_HEALTH 10

Man, those were the days.
Oh wait, those still are the days!

也许是类似于静态类的东西?

class CONSTANTS {
public:
static inline int getMana() { return 10;};
};




相关问题
热门标签