在 C++ 中,为了拥有更整洁的代码,我想在头文件中声明一组值作为常量,例如:
constexpr float SIZE_SMALL = 1.5f;
constexpr float SIZE_MEDIUM = 2.5f;
constexpr std::string COLOR_RED = "RED";
constexpr std::string MATERIAL_SILK = "SILK";
...etc
但这变得太长而且笨拙了。此外,一些常量可以组合在一起,因为它们描述相同属性的不同值,例如SIZE_SMALL
和 SIZE_MEDIUM
。
在我的头文件中写入此内容的最佳方法是什么?我考虑过结构,例如
struct SIZE
{
float SMALL;
float MEDIUM;
}
但是我必须在 .cpp 中声明并定义一个变量,这有点超出了这一切的目的。
最佳答案
then I have to declare and define a variable in my .cpp and that kinda beats the purpose of all this.
不,你不知道。您可以将字段设置为static
和constexpr
:
struct SIZES {
static constexpr const float SMALL = 1.5f;
};
但是,我建议不要这样做。您不仅不必创建此类的实例,而且也不应该创建此类的实例(为什么?)。那么为什么首先要使用类呢?使用命名空间
来对常量进行分组:
namespace SIZES {
constexpr float SMALL = 1.5f;
}
I have some 50+ of these constants in the same name space
除非你找到一种方法让编译器读懂你的想法,否则你必须把它们全部写在某个地方。说真的,唯一可以压缩的方法是这些常量之间是否存在某种关系,例如 SMALL + 1.0f = MEDIUM
,但这从您的问题中并不明显。
关于c++ - C++中类常量在哪里定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59137215/