在 C++ 的枚举中使用访问值的正确方法是什么

What is the right way to use access a value in an enumeration in C++

我在编码时遇到过这个问题,我不确定为什么会这样。 考虑这段代码

案例一

#include<iostream>

enum test{
a,b,c,d,e,f
};

int main(){
    std::cout << a;
    return 0x1;
}

案例二

#include<iostream>

enum test{
a,b,c,d,e,f
};

int main(){
    std::cout << test::a;
    return 0x1;
}

为什么代码对两者都能正确编译和执行?使用枚举时是否不需要使用 test::

不,test:: 不是必需的,因为 enum test 声明了一个 unscoped 枚举。当你定义一个 scoped 枚举时,test:: 将变得必要:

enum class test {...};

另请参阅 https://en.cppreference.com/w/cpp/language/enum 了解更多详细信息。