声明“const typedef enum”在C ++中是否有效?

时间:2016-09-15 13:18:55

标签: c++ enums const typedef

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

例如:

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

我有一个旧程序,我被迫与之合作(来自设备制造商),我一直在使用const typedef enum来定义枚举。

现在,我已经习惯了C#,所以我并不完全理解所有正在进行的C ++技巧,但这种情况似乎很简单。

从程序编码看来,Annoying类型的变量似乎无论何时何地都会被改变。

它们并不意味着不变。长话短说,编译器不喜欢它。

此示例是在2010年之前的某个时间写回来的,所以这可能是某种版本差异,但const typedef enum甚至意味着什么?

3 个答案:

答案 0 :(得分:7)

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

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

答案 1 :(得分:3)

const typedef Type def;typedef const Type def;意味着同样的事情,并且已有多年。关于Typeenum定义的情况没有什么特别之处,您也可以在其中看到它:

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

答案 2 :(得分:1)

书写

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

具有enum在C中运行良好的优势,它通过将typedef引入 typedef命名空间来处理Annoying。因此,enum声明的提供者也可以将目标定为C.

使用const限定符意味着您无法编写类似

的代码
Annoying foo = NORMAL_FUN;
foo = GREAT_FUN; // this will fail as `foo` is a `const` type.
相关问题