static const成员值与成员枚举:哪个方法更好&为什么? [英] static const Member Value vs. Member enum : Which Method is Better & Why?

查看:169
本文介绍了static const成员值与成员枚举:哪个方法更好&为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您要将某个常量值与类关联,可以通过两种方法来实现相同的目标:

If you want to associate some constant value with a class, here are two ways to accomplish the same goal:

class Foo
{
public:
    static const size_t Life = 42;
};

class Bar
{
public:
    enum {Life = 42};
};

在语法和语义上,它们从客户的角度来看似乎是相同的:

Syntactically and semantically they appear to be identical from the client's point of view:

size_t fooLife = Foo::Life;
size_t barLife = Bar::Life;

除了纯粹的风格,还有什么理由为什么会比另一个更好?

Is there any reason other than just pure style concerns why one would be preferable to another?

推荐答案

由于许多编译器不支持,所以枚举 - 值的初始化。因为这不再是一个问题,去另一个选项。现代编译器也能够优化这个常量,所以不需要存储空间。

The enum hack used to be necessary because many compilers didn't support in-place initialization of the value. Since this is no longer an issue, go for the other option. Modern compilers are also capable of optimizing this constant so that no storage space is required for it.

不使用 static const variant是如果你想禁止获取值的地址:你不能取地址枚举值,而你可以获取一个常量的地址(这将提示编译器为所有的值保留空间,但只有如果它的地址真的采取)。

The only reason for not using the static const variant is if you want to forbid taking the address of the value: you can't take an address of an enum value while you can take the address of a constant (and this would prompt the compiler to reserve space for the value after all, but only if its address is really taken).

此外,地址的获取将产生链接时间错误,除非常量显式地定义。注意它仍然可以在声明的地方初始化:

Additionally, the taking of the address will yield a link-time error unless the constant is explicitly defined as well. Notice that it can still be initialized at the site of declaration:

struct foo {
    static int const bar = 42; // Declaration, initialization.
};

int const foo::bar; // Definition.

这篇关于static const成员值与成员枚举:哪个方法更好&为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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