C ++中枚举的最佳做法 [英] Best practices for enum in C++

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

问题描述

C ++中的枚举有一个主要问题:您不能在两个不同的枚举中使用一个名称,例如:

Enums in C++ have one major problem: You can't have one name in two different enums like this:

enum Browser
{
    None = 0,
    Chrome = 1,
    Firefox = 2
}

enum OS
{
    None = 0,
    XP = 1,
    Windows7 = 2
}


b $ b

那么在这个例子中处理这个问题的最好方法是什么?

So what is the best way to handle this issue in this example?

推荐答案

您可以在 struct 内包含枚举

struct Browser
{
  enum eBrowser
  {
    None = 0,
    Chrome = 1,
    Firefox = 2
  };
};

在C ++ 11中使用枚举类

In C++11 make it an enum class:

enum class Browser
{
    None = 0,
    Chrome = 1,
    Firefox = 2
};

在C ++ 03 命名空间包装,但我个人发现包装 struct / class 更好,因为命名空间更广泛。例如

In C++03 namespace also can be wrapped, but personally I find wrapping struct/class better because namespace is more broader. e.g.

// file1.h
namespace X
{
  enum E { OK };
}

// file2.h
namespace X
{
  enum D { OK };
}

这篇关于C ++中枚举的最佳做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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