extern枚举在c ++ [英] extern enum in c++

查看:1053
本文介绍了extern枚举在c ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个枚举我已经在一些.h文件中声明:

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

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

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

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?

推荐答案

不能使用不完整的类型。你只能传递指针到它。这是因为直到类型完成,编译器不知道它有多大。 OTOH指针是数据指针的大小,无论它指向的是什么类型。

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 在一个不完整的类型中你不能做的事情是声明该类型的变量。变量声明意味着编译器将发出对另一个编译单元中提供的标识符的引用(由链接器解析),而不是分配存储。 extern 不修改类型,即使它出现在C ++语法的类型名称旁边。

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.

您可以这样做:

A.cpp

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

B.cpp

extern int var;

但类型必须匹配。你不能说 MYENUM var = TWO; 以及 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).

aside,this is incorrect:

As an aside, this is incorrect:

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

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

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

这篇关于extern枚举在c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆