声明 "const typedef enum" 在 C++ 中有效吗?

Is the declaration "const typedef enum" valid in C++?

我认为枚举是静态的,const enum 有什么意义?

例如:

const typedef enum
{
    NORMAL_FUN = 1,
    GREAT_FUN = 2,
    TERRIBLE_FUN = 3,
} Annoying;

我的头上掉了一个旧程序,我被迫使用它(来自设备制造商),而且我不断遇到用 const typedef enum.

定义的枚举

现在,我已经习惯了 C#,所以我并不完全理解所有的 C++ 技巧,但这个案例看起来很简单。

从程序的编码来看,类型为 Annoying 的变量似乎要随时随处更改。

它们并不是一成不变的。长话短说,编译器不喜欢它。

这个样本是在 2010 年之前的某个时候写回的,所以这可能是某种版本差异,但是 did/does const typedef enum 到底是什么意思?

这使得类型别名 Annoying 成为常量,因此使用该类型别名声明的所有变量都是常量:

Annoying a = NORMAL_FUN;
a = GREAT_FUN;  // Failure, trying to change a constant variable

const typedef Type def;typedef const Type def;是同一个意思,而且已经存在很多年了。 Typeenum 定义的情况没有什么特别之处,您也可以在以下位置看到它:

const typedef int const_int;
const_int i = 3;
i = 4; // error

写作

typedef enum
{
    NORMAL_FUN = 1,
    GREAT_FUN = 2,
    TERRIBLE_FUN = 3,
} Annoying;

的优点是 enum 在 C 中也能很好地工作,它通过将 Annoying 引入 typedef 命名空间 来处理 typedef。因此 enum 声明的提供者 可能 也以 C.

为目标

使用const限定符意味着你不能写出像

这样的代码
Annoying foo = NORMAL_FUN;
foo = GREAT_FUN; // this will fail as `foo` is a `const` type.