c++ 中的外部枚举

发布于 2024-10-21 00:09:03 字数 301 浏览 6 评论 0原文

我在某个 .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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

埋葬我深情 2024-10-28 00:09:03

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

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


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

所以你可以这样做:

A.cpp

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

B.cpp

extern int var;

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


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

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

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

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

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).


As an aside, this is incorrect:

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

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

前事休说 2024-10-28 00:09:03

如果枚举值不可见,则不能使用它们。如果标头太大而无法包含,为什么不将枚举放入其自己的标头中,并仅包含该标头?

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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文