是否有理由使用枚举在C ++代码中定义单个常量? [英] Is there a reason to use enum to define a single constant in C++ code?

查看:210
本文介绍了是否有理由使用枚举在C ++代码中定义单个常量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在函数中定义一个整数常量的典型方法是:

The typical way to define an integer constant to use inside a function is:

const int NumbeOfElements = 10;

在类中使用:

class Class {
...
    static const int NumberOfElements = 10;
};

它可以用作固定大小的数组边界,这意味着它在编译时是已知的。

It can then be used as a fixed-size array bound which means it is known at compile time.

很久以前,编译器不支持后一种语法,这就是为什么使用枚举:

Long ago compilers didn't support the latter syntax and that's why enums were used:

enum NumberOfElementsEnum { NumberOfElements = 10; }

现在几乎每个广泛使用的编译器支持函数 const int 和in-class static const int 语法有什么理由使用枚举为此目的?

Now with almost every widely used compiler supporting both the in-function const int and the in-class static const int syntax is there any reason to use the enum for this purpose?

推荐答案

原因主要是简洁。首先,枚举可以是匿名的:

The reason is mainly brevity. First of all, an enum can be anonymous:

 class foo {
    enum { bar = 1 };
 };

这有效地引入了 bar 。注意,上面的例子比 static const int 要短。

This effectively introduces bar as an integral constant. Note that the above is shorter than static const int.

$ c>& bar 如果它是一个枚举成员。如果你这样做:

Also, no-one could possibly write &bar if it's an enum member. If you do this:

 class foo {
    static const int bar = 1;
 }

,然后您的类的客户端执行此操作:

and then the client of your class does this:

 printf("%p", &foo::bar);

那么他将得到一个编译时链接器错误 foo :: bar 未定义(因为,​​好,作为左值,它不是)。在实践中,使用当前标准,任何 bar 用于整数常数表达式不是必需(即, ),它需要一个超类的定义 foo :: bar。需要这样的表达式的地方是: enum initializers, case 标签,类型中的数组大小(除了 new [] )和模板参数积分类型。因此,在任何地方使用 bar 在技术上需要定义。有关详情,请参见 C ++核心语言版本712

then he will get a compile-time linker error that foo::bar is not defined (because, well, as an lvalue, it's not). In practice, with the Standard as it currently stands, anywhere bar is used where an integral constant expression is not required (i.e. where it is merely allowed), it requires an out-of-class definition of foo::bar. The places where such an expression is required are: enum initializers, case labels, array size in types (excepting new[]), and template arguments of integral types. Thus, using bar anywhere else technically requires a definition. See C++ Core Language Active Issue 712 for more info - there are no proposed resolutions as of yet.

在实践中,这些日子里的大多数编译器对此更加宽松,并且会让你在最常见的情况下使用 static const int 变量,而不需要定义。然而,角落的情况可能不同,但是,许多人认为只是使用匿名枚举是更好的,一切都是清楚的,并且没有歧义。

In practice, most compilers these days are more lenient about this, and will let you get away with most "common sense" uses of static const int variables without requiring a definition. However, the corner cases may differ, however, so many consider it to be better to just use anonymous enum, for which everything is crystal clear, and there's no ambiguity at all.

这篇关于是否有理由使用枚举在C ++代码中定义单个常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆