本文介绍了C ++最好的方法来定义跨文件常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在玩游戏,有一个有趣的问题。我有一些游戏范围的常数值,我想在一个文件中实现。现在我有这样的:

I am working on a game and have an interesting question. I have some game-wide constant values that I want to implement in one file. Right now I have something like this:

constants.cpp

constants.cpp

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

constants.hpp

constants.hpp

extern const int BEGINNING_HEALTH;
extern const int BEGINNING_MANA;

然后文件只是#includeconstants.hpp
这是非常好的,直到我需要使用其中一个常量作为模板参数,因为外部链接的常量不是有效的模板参数。
所以我的问题是,什么是最好的方式来实现这些常量?恐怕简单地将常数放在头文件中将导致它们在每个翻译单元中定义。

And then files just #include "constants.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.

感谢

推荐答案

除去 extern 并设置。

此代码在标题中工作的很好,因为一切都是真正的恒定,因此具有内部链接:

This code works perfectly fine in a header, because everything is "truly constant" and therefore has internal linkage:

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

此代码不能安全地放在头文件中,因为每行都有外部链接不真正恒定):

This code cannot safely be put in a header file because each line has external linkage (either explicitly or because of not being truly constant):

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

这篇关于C ++最好的方法来定义跨文件常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 00:00