您应该在类的内部还是外部声明枚举? [英] Should you declare enums inside or outside a class?
问题描述
如果仅在类成员函数中使用枚举,应该在类的内部还是外部声明枚举?
namespace nspace
{
// need to append OC, as this pollutes the current namespace
enum OUTSIDE_CLASS {OC_POINTS, OC_LINES, OC_LINE_LOOP, :::};
enum OTHER_ENUM {OE_POINTS};
class VertexBuffer
{
public:
enum INSIDE_CLASS {POINTS, LINES, LINE_LOOP, :::};
void foo(OUTSIDE_CLASS e);
void bar(INSIDE_CLASS e);
}
};
// usage
nspace::VertexBuffer v;
v.foo(nspae::VB_POINTS);
v.bar(nspace::VertexBuffer::POINTS); // more pedantic
真正的目标是避免污染范围(全局或命名空间),并帮助将相关值组合在一起(在IDE中使用自动补全实现漂亮的商品).>
对于C ++ 11,您可以使用以下方法声明强类型的枚举:
enum class MyEnum {
Value0,
Value1
};
,必须以MyEnum::Value0
(而不是Value0
)调用.
在C ++ 03中,您可以通过以下方式或多或少地对此进行仿真:
struct MyEnum {
enum Type {
Value0,
Value1
};
};
但是,枚举的类型是MyEnum::Type
,这是完全不同的.
懒惰的选择是将其转储到一个类中,但是我仍然赞成嵌套一个有作用域的枚举,即使是在一个类中,也只是为了清楚地表明这些值不是 loose 而是相互关联.
Should you declare enums inside or outside a class if the said enums are only used in the class member functions?
namespace nspace
{
// need to append OC, as this pollutes the current namespace
enum OUTSIDE_CLASS {OC_POINTS, OC_LINES, OC_LINE_LOOP, :::};
enum OTHER_ENUM {OE_POINTS};
class VertexBuffer
{
public:
enum INSIDE_CLASS {POINTS, LINES, LINE_LOOP, :::};
void foo(OUTSIDE_CLASS e);
void bar(INSIDE_CLASS e);
}
};
// usage
nspace::VertexBuffer v;
v.foo(nspae::VB_POINTS);
v.bar(nspace::VertexBuffer::POINTS); // more pedantic
The real goal is to avoid polluting the scope (either global or namespace) and help grouping related values together (works pretty goods with autocompletion in IDE).
With C++11, you can declare strongly typed enums using:
enum class MyEnum {
Value0,
Value1
};
which are necessarily invoked as MyEnum::Value0
(and not Value0
).
In C++03, you can more or less emulate this with:
struct MyEnum {
enum Type {
Value0,
Value1
};
};
But then the type of the enum is MyEnum::Type
which is subtly different.
The lazy option is to just dump it in a class, but I still favor nesting a scoped enum, even within a class, just to make it clear that those values are not loose but instead are inter-related.
这篇关于您应该在类的内部还是外部声明枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!