c++ - C++中类常量在哪里定义?

标签 c++ header refactoring constants compile-time-constant

在 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_SMALLSIZE_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.

不,你不知道。您可以将字段设置为staticconstexpr:

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/

相关文章:

c++ - "No match for operator="试图在 C++ 中遍历映射

c++ - Boost Asio HTTPS 请求给出 'certificate verify failed' 错误

c++ - 如何在cygwin中安装和使用NTL

Python 值错误 : Invalid header name b':authority

c - 枚举和结构定义

view - SwiftUI 中的数据流与@EnvironmentObject

c++ - 基于 pthread 的多功能多线程实用程序库

c++ - 微软 Visual Studio 社区 2017 的 Graphics.h

c# - 如何重构 linq 查询以重用其部分

c# - 重构以将 NameValueCollection 和 KeyValueConfigurationCollection 作为参数?