在类中声明枚举 [英] Declaring an enum within a class
问题描述
在以下代码片段中, Car
类中声明 Color
枚举,并尝试不污染全局命名空间。
class Car
{
public:
enum Color
{
RED,
BLUE,
WHITE
};
void SetColor(Car :: Color color)
{
_color = color;
}
Car :: Color GetColor()const
{
return _color;
}
private:
Car :: Color _color;
};
(1)这是一个很好的方法来限制 Color
枚举?或者,我应该在 Car
类之外声明它,但可能在它自己的命名空间或结构中?我今天刚刚看到这篇文章,它主张后者,并讨论一些关于枚举的好点: http://gamesfromwithin.com/stupid-c-tricks-2-better-enums 。
(2)在此示例中, c $ c>够了吗? (我假设前者更好,只是为了在全局命名空间中声明另一个 Color
枚举,这样,我们至少明确了枚举
-
如果
Color
是特定于Car
的这就是你限制其范围的方式。如果你要另一个Color
枚举其他类使用,那么你可以使它是全局的(或至少在Car
)。 -
这没什么区别。如果有一个全局变量,那么局部变量仍然被使用,因为它更接近当前范围。注意,如果你在类定义之外定义这些函数,你需要在函数的接口中明确指定
Car :: Color
。
In the following code snippet, the Color
enum is declared within the Car
class in order to limit the scope of the enum and to try not to "pollute" the global namespace.
class Car
{
public:
enum Color
{
RED,
BLUE,
WHITE
};
void SetColor( Car::Color color )
{
_color = color;
}
Car::Color GetColor() const
{
return _color;
}
private:
Car::Color _color;
};
(1) Is this a good way to limit the scope of the Color
enum? Or, should I declare it outside of the Car
class, but possibly within its own namespace or struct? I just came across this article today, which advocates the latter and discusses some nice points about enums: http://gamesfromwithin.com/stupid-c-tricks-2-better-enums.
(2) In this example, when working within the class, is it best to code the enum as Car::Color
, or would just Color
suffice? (I assume the former is better, just in case there is another Color
enum declared in the global namespace. That way, at least, we are explicit about the enum to we are referring.)
Thanks in advance for any input on this.
If
Color
is something that is specific to justCar
s then that is the way you would limit its scope. If you are going to have anotherColor
enum that other classes use then you might as well make it global (or at least outsideCar
).It makes no difference. If there is a global one then the local one is still used anyway as it is closer to the current scope. Note that if you define those function outside of the class definition then you'll need to explicitly specify
Car::Color
in the function's interface.
这篇关于在类中声明枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!