c++ 中的外部枚举
我在某个 .h 文件中声明了一个枚举:
typedef enum {
NONE,
ONE,
TWO,
THREE
} MYENUM;
在单独的 .cpp 中我无法执行此操作:
extern enum MYENUM; //works
extern MYENUM TWO; //makes sence, TWO is not an INSTANCE of MYENUM...
如果不包含声明枚举的整个标头,将如何执行此操作?
I have an enum I have declared in some .h file:
typedef enum {
NONE,
ONE,
TWO,
THREE
} MYENUM;
in a seperate .cpp I cannot do this:
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不能使用不完整的类型。您只能传递指向它的指针。这是因为在类型完成之前,编译器不知道它有多大。 OTOH 指针的大小就是数据指针的大小,无论它指向什么类型。对于不完整类型不能做的事情之一就是声明该类型的变量。
变量声明中的 extern 意味着编译器将发出对另一个编译单元中提供的标识符的引用(由链接器解析),而不是分配存储。
extern
不会修改类型,即使它出现在 C++ 语法中的类型名称旁边。您可以做的是利用枚举成员是整型常量值的事实,并将其很好地转换为原始整型类型。
所以你可以这样做:
A.cpp
B.cpp
但类型必须匹配。您不能说
MYENUM var = TWO;
也不能说extern int var;
。这将违反单一定义规则(链接器可能会也可能不会检测到违规)。顺便说一句,这是不正确的:
MYENUM
不是枚举标识符。它是一个 typedef,以后不能用enum
关键字限定。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.
extern
in 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.extern
does not modify the type, even if it appears next to the type name in C++ grammar.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
B.cpp
But the types must match. You couldn't say
MYENUM var = TWO;
and alsoextern int var;
. That would violate the one-definition-rule (violation might or might not be detected by the linker).As an aside, this is incorrect:
MYENUM
is NOT an enum identifier. It is a typedef, and cannot be qualified with theenum
keyword later.如果枚举值不可见,则不能使用它们。如果标头太大而无法包含,为什么不将枚举放入其自己的标头中,并仅包含该标头?
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?