简体   繁体   English

为什么我可以引用仅前向声明的枚举成员

[英]Why can I reference a member of an enum that is only forward declared

For example, given the following:例如,给定以下内容:

// enum.h
enum class TestEnum: int {
    ONE,
    TWO,
    THREE
};
// function.h
enum class TestEnum: int;
int TestFunction(TestEnum te = TestEnum::THREE);
// function.cpp
#include "enum.h"
#include "function.h"

int TestFunction(TestEnum te) { 
    return 5;
}

In my eyes this should not compile because in function.h, with TestEnum only being forward declared, the compiler cannot know that TestEnum::THREE (which is used as a default argument for TestFunction ) is a valid member of the enum.在我看来,这不应该编译,因为在 function.h 中,只向前声明了TestEnum ,编译器无法知道TestEnum::THREE (用作TestFunction的默认参数)是枚举的有效成员。 And yet it does.然而它确实如此。

If I forward declare a class, I cannot access its members, but with enums it seems I can.如果我转发声明 class,我将无法访问其成员,但使用枚举似乎可以。 Why is that?这是为什么? And is this something "legal" as per the standard, or did it just happen to work because of the way the compilers I tried (clang and gcc) are implemented?这是按照标准“合法”的东西,还是因为我尝试的编译器(clang 和 gcc)的实现方式而恰好起作用?

Header files are not compiled. Header 文件未编译。 Source files are.源文件是。

Within your function.cpp file, you first include enum.h, which contains TestEnum, and then you include function.h.在 function.cpp 文件中,首先包含 enum.h,其中包含 TestEnum,然后包含 function.h。

From the compiler point of view, it copy paste the content of those header files on top of your source file, so you do have access to the scoped value of the enum when your compiler arrives on the function.cpp file.从编译器的角度来看,它将那些 header 文件的内容复制粘贴到源文件的顶部,因此当编译器到达 function.cpp 文件时,您确实可以访问枚举的作用域值。

However, this would not work if the order of inclusion was first function.h and finally enum.h because the compiler could not know the content (here the scoped value of the enum) of TestEnum.但是,如果包含顺序首先是 function.h,最后是 enum.h,这将不起作用,因为编译器无法知道 TestEnum 的内容(这里是枚举的作用域值)。 This is the same behavior when you fast forward a class and try to access its members.这与您快进 class 并尝试访问其成员时的行为相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM