因此,请考虑以下结构:
struct CType
{
enum DType
{
Int,
Char
} Type;
union Value
{
int num;
char alpha;
Value() {
this->num = 0;
this->alpha = '\0';
};
~Value() {};
} value;
};
我怎样才能做到这一点?
CType u3;
u3.Type = CType::Int;
为什么上面的工作?
我本来可以这样做:
u3.Type = CType::DType::Int;
提前致谢。
最佳答案
DType
是一个无范围的枚举,在其包围范围内可见:
无作用域枚举(重点是我)-C++ 11之前的版本:
Each enumerator becomes a named constant of the enumeration's type (that is, name), visible in the enclosing scope, and can be used whenever constants are required.
您正在寻找范围枚举(自C++ 11起可用):
Each enumerator becomes a named constant of the enumeration's type (that is, name), which is contained within the scope of the enumeration, and can be accessed using scope resolution operator. There are no implicit conversions from the values of a scoped enumerator to integral types, although static_cast may be used to obtain the numeric value of the enumerator.
请参阅文档:https://en.cppreference.com/w/cpp/language/enum
因此,
DType
作为范围枚举将是:enum class DType { Int, Char };
并且,可以像这样从中访问
Int
:DType::Int
关于c++ - 从类(class)访问枚举成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61870828/