两个枚举有一些共同元素,为什么会产生错误?
我的代码中有两个枚举:
enum Month {January, February, March, April, May, June, July,
August, September, October, November, December};
enum ShortMonth {Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec};
May
是两个枚举中的公共元素,因此编译器表示:
重新声明枚举器“
May
”。
为什么这么说呢?我该如何规避这个问题?
I have two enums in my code:
enum Month {January, February, March, April, May, June, July,
August, September, October, November, December};
enum ShortMonth {Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec};
May
is a common element in both enums, so the compiler says:
Redeclaration of enumerator '
May
'.
Why does it say so? And how can I circumvent this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
枚举名称在全局范围内,它们需要是唯一的。请记住,您不需要使用枚举名称来限定枚举符号,您只需:而
不是:
因此,您经常会看到人们在符号名称前添加枚举名称作为前缀:
Enum names are in global scope, they need to be unique. Remember that you don't need to qualify the enum symbols with the enum name, you do just:
not:
For this reason, you often see people prefixing the symbol names with the enum's name:
我建议你将两者合并:
效果完全相同,而且更方便。
如果您希望一月的值为 1 而不是 0,请添加以下内容:
I suggest you merge the two:
Which will have exactly the same effect, and is more convenient.
If you want January to have the value 1, instead of 0, add this:
在 C++ 中,为了避免名称冲突,您可以将枚举包装到结构中:
In C++, to avoid name clashing you could wrap your enums into structs:
在 C++11 中,您可以使用 作用域枚举 来解决此问题。这将从全局范围中删除名称并将其范围限制为枚举名称。
实例
In C++11 you can use scoped enumerations to fix this this. This will remove the names from the global scope and scope them to the enum name.
Live Example
放松说什么。但我还想说,您的示例似乎是枚举的非常不寻常的使用。我看不出 ShortMonth 和 LongMonth 都引用同一事物的价值 - 这对于字符串有意义,但对于枚举则不然。为什么不只有一个 Month 枚举类型呢?
What unwind said. But I'd also like to say that your example seems like a pretty unusual use of enums. I can't see the value of having a ShortMonth and a LongMonth both referring to the same thing - this would make sense for strings, but not for enums. Why not just have a single Month enum type?
我的建议是只使用一个枚举,因为它们是同一类型。如果您希望短别名在代码中少输入(即使我不建议您这样做),您可以这样做:
并且要具有不同的表示名称(短和长),您应该有两个不同的字符串数组,它们是由枚举索引。
My suggestion here is to have just one enum, as they are the same type. If you want short aliases to type less in your code (even if I wouldn't advise you to do so), you can do:
And to have different presentation names (short and long), you should have two distinct string arrays that are indexed by the enum.
在 C 中,枚举的使用没有任何类型前缀,因此您可以这样写:
枚举 Month 和 ShortMonth 具有相同的作用域,因此编译器无法知道要使用哪个 May。一个明显的解决方法是为枚举添加前缀,但我不确定在这种情况下使用这些枚举是否合理。
In C enums are used without any type prefix, so you write:
The enum Month and ShortMonth have the same scope so the compiler can't know which May to use. An obvious fix would be to prefix the enums but i'm not sure that your use of these enums in this case is warranted.
将它们合并为一
Merge them become one