问题
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
回答1:
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.
回答2:
If only your class members use the enum it is preferable to declare the enum inside the class.
This prevents the namespace/global space from pollution due to unneeded symbol names & also
It is more intutive for users of the class, it helps the user to know that the enum will only be used by the class.
The general rule you should follow is:
Do not add any symbol in a scope(global/namespace) which will not be accessed(& hence not needed) in that scope.
回答3:
As Matthieu M. mentioned, in C++11 use Strongly typed enumerations.
A good way to emulate them in C++03 is to wrap enums in namespaces. It is better than wrapping in a struct because that namespace may have functions that can be found using argument-dependent name lookup. E.g.:
namespace MyEnum {
enum Type {
Value0,
Value1
};
std::ostream& operator<<(std::ostream&, Type);
std::istream& operator>>(std::istream&, Type&);
}
MyEnum::Type value;
std::cout << value; // uses the overload from MyEnum
std::cin >> value; // uses the overload from MyEnum
回答4:
It depends. Strive to minimize exposure of implementation details. E.g. enclose things in namespaces and/or classes and/or separately compiled implementation files. And as that hopefully makes very clear, the global namespace and in-class are absolutely not the only options. I.e., declaring something in-class is not the only way to minimize exposure (what are some other ways then? --- oh, well, remember the third sentence of this answer).
来源:https://stackoverflow.com/questions/9630744/should-you-declare-enums-inside-or-outside-a-class