rlb*_*ond 10 c++ templates const constants extern
我正在开发一款游戏并且有一个有趣的问题.我有一些游戏范围的常量值,我想在一个文件中实现.现在我有这样的事情:
constants.cpp
extern const int BEGINNING_HEALTH = 10;
extern const int BEGINNING_MANA = 5;
Run Code Online (Sandbox Code Playgroud)
constants.hpp
extern const int BEGINNING_HEALTH;
extern const int BEGINNING_MANA;
Run Code Online (Sandbox Code Playgroud)
然后文件只是#include"constants.hpp"这很好用,直到我需要使用其中一个常量作为模板参数,因为外部链接的常量不是有效的模板参数.所以我的问题是,实现这些常量的最佳方法是什么?我担心简单地将常量放在头文件中会导致在每个翻译单元中定义它们.而且我不想使用宏.
谢谢
Tom*_*Tom 19
摆脱extern你和你的设置.
这个代码在头文件中工作得非常好,因为所有内容都是"真正的常量",因此具有内部链接:
const int BEGINNING_HEALTH = 10;
const int BEGINNING_MANA = 5;
const char BEGINNING_NAME[] = "Fred";
const char *const BEGINNING_NAME2 = "Barney";
Run Code Online (Sandbox Code Playgroud)
此代码无法安全地放入头文件中,因为每行都有外部链接(显式或因为不是真正的常量):
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
Run Code Online (Sandbox Code Playgroud)
小智 10
枚举怎么样?
constants.hpp
enum {
BEGINNING_HEALTH = 10,
BEGINNING_MANA = 5
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11670 次 |
| 最近记录: |