使用Enum存储数值常量

Using Enum to store numerical constants

本文关键字:常量 存储 Enum 使用      更新时间:2023-10-16

我最近遇到类似下面的代码:

#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