命名空间中的枚举 [英] enum in a namespace

查看:413
本文介绍了命名空间中的枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有必要做这样的事情:

Is there a point of doing somthing like this:

namespace status{
  enum status{
    ok,
    error
  };
}

并像这样使用它status::ok

还是我应该这样做:

enum status{
  status_ok,
  status_error
};

并像这样使用它status_ok?

更新: 使用C ++ 11,您现在应该执行以下操作:

Update: With C++11 you now should do this:

enum class status {
    ok,
    error
};

并像这样使用:status::ok

推荐答案

我个人不喜欢第二个变体,因为status_部分对我来说似乎是多余的.前一个版本避免了该问题,但是具有类型status::status看起来也很奇怪.此外,命名空间可以进行修改,因此,如果有人做了类似的事情

I personally don't like the second variation because the status_ part seems redundant to me. The former version avoids that problem, but having a type status::status looks strange too. Furthermore, a namespace is open to modification, so in case somebody did something like

namespace status {
  void error( const char *msg );
}

由于函数error与您的enum值冲突,因此会出现编译器错误.

You would get a compiler error since the function error clashes with your enum value.

我更喜欢使用第三个变体:

I prefer to use a third variation:

struct MouseButton {
  enum Value {
    Left, Middle, Right
  };
};

这让我编写了类似的功能

This lets me write functions like

void handleMouseButton( MouseButton::Value b ) {
  switch ( b ) {
    case MouseButton::Left:   // ...
    case MouseButton::Middle: // ...
    case MouseButton::Right:  // ...
  }
}

这篇关于命名空间中的枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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