C++ 我的枚举不是类或命名空间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5188554/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
My enum is not a class or namespace
提问by Prof
Hi I have files called MyCode.h and MyCode.cpp
嗨,我有名为 MyCode.h 和 MyCode.cpp 的文件
In MyCode.h I have declared
在 MyCode.h 我已经声明
enum MyEnum {Something = 0, SomethingElse = 1};
class MyClass {
MyEnum enumInstance;
void Foo();
};
Then in MyCode.cpp:
然后在 MyCode.cpp 中:
#include "MyCode.h"
void MyClass::Foo() {
enumInstance = MyEnum::SomethingElse;
}
but when compiling with g++ I get the error 'MyEnum' is not a class or namespace...
但是当使用 g++ 编译时,我收到错误“MyEnum”不是类或命名空间...
(works fine in MS VS2010 but not linux g++)
(在 MS VS2010 中工作正常,但在 linux g++ 中无效)
Any ideas? Thanks Thomas
有任何想法吗?谢谢托马斯
回答by Max Lybbert
The syntax MyEnum::SomethingElse
is a Microsoft extension. It happens to be one I like, but it's not Standard C++. enum
values are added to the surrounding namespace:
语法MyEnum::SomethingElse
是 Microsoft 扩展。它恰好是我喜欢的一种,但它不是标准 C++。 enum
值被添加到周围的命名空间:
// header
enum MyEnum {Something = 0, SomethingElse = 1};
class MyClass {
MyEnum enumInstance;
void Foo();
}
// implementation
#include "MyClass.h"
void Foo() {
enumInstance = SomethingElse;
}
回答by ildjarn
Scoped enums will not exist until C++0x. For the time being, your code should be
作用域枚举直到 C++0x 才存在。目前,您的代码应该是
enumInstance = SomethingElse;
You can create an artificial scoped enum by putting the enum's definition inside its own namespace or struct.
您可以通过将枚举的定义放在其自己的命名空间或结构中来创建人工作用域枚举。
回答by gregn3
Indeed, C++0x allows that feature. I could enable it successfully in gcc using this command line flag: -std=c++0x
事实上,C++0x 允许这个特性。我可以使用以下命令行标志在 gcc 中成功启用它:-std=c++0x
This was with gcc version 4.4.5
这是 gcc 版本 4.4.5
回答by Jonathan
As explain in other answers: syntax MyEnum::SomethingElse
is not valid on regular C++98 enums unless your compiler supports them through non-standard extensions.
正如其他答案中所解释的:MyEnum::SomethingElse
除非您的编译器通过非标准扩展支持它们,否则语法在常规 C++98 枚举上无效。
I personally don't like the declaration enum MyEnum {A, B};
because Type name is not present while using enum values. This can leads to conflict of names in the current name space.
我个人不喜欢这个声明,enum MyEnum {A, B};
因为在使用枚举值时不存在类型名称。这可能会导致当前名称空间中的名称冲突。
So user should refer to the type name at each enum values. Example to avoid declaring A twice:
所以用户应该在每个枚举值中引用类型名称。避免声明 A 两次的示例:
enum MyEnum {MyEnum_A, MyEnum_B};
void A(void) {
MyEnum enumInstance = MyEnum_A;
}
I prefer to use a specific name space or structure. This allow to reference enum values with latest C++ style:
我更喜欢使用特定的名称空间或结构。这允许使用最新的 C++ 样式引用枚举值:
namespace MyEnum {
enum Value {A,B};
}
void A(void) {
MyEnum::Value enumInstance = MyEnum::A
}