关于C ++:枚举前向声明与头文件

Enum forward declaration vs. header files

在LearnCPP CH4.5枚举类型中,它指出

Because the compiler needs to know how much memory to allocate for an enumeration, you cannot forward declare enum types. However, there is an easy workaround. Because defining an enumeration does not allocate any memory, if an enumeration is needed in multiple files, it is fine to define the enumeration in a header, and #include that header wherever needed.

我认为头文件是前向声明的集合,但只是在一个单独的文件中。 那么,为什么在头文件中声明枚举类型与在同一文件中正使用声明枚举类型有所不同呢?


这里的声明不是真正关于枚举的声明位置,而是声明和定义之间的区别。

就像是

1
2
3
4
5
enum MyEnum; // just a declaration, not a definition

struct Foo {
    MyEnum value;
};

无法编译,因为编译器无法仅通过声明来确定MyEnum的大小,而是需要该大小来确定上面代码段中定义的struct Foo的大小。

这与类似

1
2
3
4
5
6
7
8
9
10
11
// the following is both a declaration and a defintion of the enum `MyEnum`
enum MyEnum {
    your,
    enumerators,
    go,
    here
};

struct Foo {
  MyEnum value;
};

之所以进行编译,是因为编译器现在具有确定struct Foo的大小所需的所有信息。

但是,您引用的来源似乎有些过时了。 从C ++ 11开始,只要知道枚举的大小就可以满足声明,即因为您明确指定了无范围的枚举的基础类型(例如enum MyEnum : unsigned int;),或者因为您使用了范围限定的枚举,默认情况下 使用int作为其基础类型。 那是

1
2
3
4
5
6
7
enum MyEnum : int; // declaration only, but with specified underlying type
enum class Bar;  // also only declaration, `int` is implicit underlying type

struct Foo {
    MyEnum v1;
    Bar v2;
};

编译就好了。