C++ 枚举前向声明
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15141248/
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
Enum Forward Declaration
提问by anatolyg
I'm trying to use correctly forward declaration for enums. Therefore I searched the internet but I can't find something that works.
我正在尝试为枚举正确使用前向声明。因此,我搜索了互联网,但找不到有效的东西。
I'm using in a header :
我在标题中使用:
// Forward declaration
enum myEnumProcessState;
I'm then using this enum in a struct :
然后我在结构中使用这个枚举:
struct myStruct {
[...]
myEnumProcessState osState;
[...]
};
And in another header :
在另一个标题中:
enum myEnumProcessState {
eNotRunning,
eRunning
};
I found out that the type should be put in the enum forward declaration to be accepted. However I don't know which "type" I should put for a Process State. These don't work :
我发现该类型应该放在枚举前向声明中才能被接受。但是我不知道应该为进程状态放置哪种“类型”。这些不起作用:
enum myEnumProcessState : unsigned int;
enum myEnumProcessState : String;
I wanted to skip the forward declaration but my Struct is crying since it can't find it anymore ...
我想跳过前向声明,但我的 Struct 正在哭泣,因为它再也找不到了......
So I'm a bit confused. Do you know a solution ?
所以我有点困惑。你知道解决办法吗?
Many thanks :)
非常感谢 :)
回答by anatolyg
Before C++11, C++ didn't support forward-declaration of enums at all! However, some compilers (like MS Visual Studio) provide language extensions for that.
在 C++11 之前,C++ 根本不支持枚举的前向声明!但是,一些编译器(如 MS Visual Studio)为此提供了语言扩展。
If your compiler doesn't support C++11, look in its documentation on enum forward declarations.
如果您的编译器不支持 C++11,请查看其有关枚举前向声明的文档。
If you can use C++11, there is the enum class
syntax (you almost got it right, but pay attention to the additional class
keyword:
如果您可以使用 C++11,则有enum class
语法(您几乎猜对了,但请注意附加class
关键字:
// Forward declaration
enum class myEnumProcessState: unsigned int;
// Usage in a struct
struct myStruct {myEnumProcessState osState;};
// Full declaration in another header
enum class myEnumProcessState: unsigned int {
eNotRunning,
eRunning
};
// Usage of symbols (syntax may seem slightly unusual)
if (myObject.osState == myEnumProcessState::eNotRunning) {
...
}