使用Enum存储数值常量
Using Enum to store numerical constants
我最近遇到类似下面的代码:
#include <stdio.h>
class Example {
private:
enum {
BufSize = 4096,
MsgSize = 200 * 1024,
HeaderFieldLen = 16
};
public:
int getBufSize() {
return BufSize;
}
};
int main() {
Example ex;
printf("%dn", ex.getBufSize());
return 0;
}
类本质上是将常量存储在enum中,并在其成员函数中使用其值。
这是枚举的有效使用吗?如果是,是否有任何理由以这种方式存储常量,而不是在struct
或常规const
类成员变量中存储常量?
有几种命名数字常量的方法,以避免魔术数字。使用枚举数就是其中之一。
与常规const
变量相比,该方法的优点是枚举数不是变量。因此,它们不会在运行时作为变量存储,它们只是在编译时由编译器使用。
[from the comments]
所以这种用法在某些方面类似于使用预处理器宏来定义常量?
宏的缺点(主要)是类型安全。宏没有类型,因此编译器无法为您检查类型是否与使用它们的地方匹配。此外,虽然在C中使用宏,但在c++中很少使用宏,因为我们有更好的工具可以使用。
在c++ 11中,更好的命名这些常量的方法是使用constexpr
成员。
constexpr int BufSize = 4096;
constexpr int MsgSize = 200 * 1024;
constexpr int HeaderFieldLen = 16;
上面的代码替换了下面的代码。
enum {
BufSize = 4096,
MsgSize = 200 * 1024,
HeaderFieldLen = 16
};
有效
在早期,并不是所有的编译器都很好地支持static const data member
。因此,您必须使用enum
hack来模拟静态const整型数据成员。
现在,由于编译器已经很好地支持static const data member
,所以您不必使用此hack。
// in example.h
class Example {
static const int BufSize = 4096;
};
// in example.cpp
const int Example::BufSize; // definition
相关文章:
- 如何为静态常量模板化专用整数值分配存储
- 常量参数存储在哪里 (C++)?
- 如何在可执行文件中存储常量数组?
- 具有静态存储持续时间的常量初始化变量的初始化顺序
- 有没有办法在类实例中存储编译时常量?
- c++ 类中的静态常量变量和常量变量在存储方面是否有区别
- 如何最好地初始化和存储常量对象
- 在不同翻译单元中具有静态存储持续时间的依赖非局部常量浮点变量的常量初始化
- 在 c++ 中存储文本常量
- std::to_string 存储在常量字符*中
- c++中用于常量数据的内存存储
- 常量存储在何处以及如何存储
- 传递给存储常量引用的成员的临时对象的生存期
- 如何将升压随机数生成器的状态存储为常量字符 *
- 其中C++内存中的文字常量存储
- 常量数据存储在哪里
- 如何将常量字符*存储到字符*
- 测试静态常量成员的存储位置
- 在类中存储对对象的常量引用
- 如何将常量存储在变量中