C++ 中的外部枚举

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5224150/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:43:26  来源:igfitidea点击:

extern enum in c++

c++syntaxcompilationexternlinkage

提问by Tom Fobear

I have an enum I have declared in some .h file:

我在一些 .h 文件中声明了一个枚举:

typedef enum {
    NONE,
    ONE,
    TWO,
    THREE
} MYENUM;

in a seperate .cpp I cannot do this:

在单独的 .cpp 中,我不能这样做:

extern enum MYENUM; //works
extern MYENUM TWO; //makes sence, TWO is not an INSTANCE of MYENUM...

how would one do so without including the whole header where the enum is declared?

如果不包括声明枚举的整个标头,将如何做到这一点?

采纳答案by Ben Voigt

You can't use an incomplete type. You can only pass around pointers to it. This is because until the type is completed, the compiler doesn't know how big it is. OTOH a pointer is the size of a data pointer, no matter what type it's pointing to. One of the things you can't do with an incomplete type is declare variables of that type.

您不能使用不完整的类型。您只能传递指向它的指针。这是因为直到类型完成,编译器才知道它有多大。OTOH 指针是数据指针的大小,无论它指向什么类型。您不能对不完整类型做的一件事是声明该类型的变量。

externin a variable declaration means that the compiler will emit a reference to an identifier provided in another compilation unit (to be resolved by the linker), instead of allocating storage. externdoes not modify the type, even if it appears next to the type name in C++ grammar.

extern在变量声明中意味着编译器将发出对另一个编译单元中提供的标识符的引用(由链接器解析),而不是分配存储。 extern不会修改类型,即使它出现在 C++ 语法中的类型名称旁边。



What you can do is take advantage of the fact that enum members are integral constant values, and convert just fine to the primitive integral types.

您可以做的是利用枚举成员是整数常量值这一事实,并将其转换为原始整数类型。

So you can do this:

所以你可以这样做:

A.cpp

A.cpp

enum MYENUM { ONE=1, TWO, THREE };
int var = TWO;

B.cpp

B.cpp

extern int var;

But the types must match. You couldn't say MYENUM var = TWO;and also extern int var;. That would violate the one-definition-rule (violation might or might not be detected by the linker).

但类型必须匹配。你不能说MYENUM var = TWO;extern int var;。这将违反单一定义规则(链接器可能会或可能不会检测到违规)。



As an aside, this is incorrect:

顺便说一句,这是不正确的:

typedef enum {
    NONE,
    ONE,
    TWO,
    THREE
} MYENUM;
enum MYENUM TWO;

MYENUMis NOT an enum identifier. It is a typedef, and cannot be qualified with the enumkeyword later.

MYENUM不是枚举标识符。它是一个 typedef,enum以后不能用关键字限定。

回答by Bo Persson

You cannot use enum values, if they are not visible. If the header is too large to include, why not just put the enum in its own header, and include only that?

如果枚举值不可见,则不能使用它们。如果标题太大而无法包含,为什么不将枚举放在它自己的标题中,并且只包含那个?