c++ - 从类(class)访问枚举成员

标签 c++

因此,请考虑以下结构:

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/

相关文章:

C++, Linux : error: conversion from ‘boost::unique_future<void>’ to non-scalar type ‘boost::shared_future<void>’ requested. 如何绕过它?

c++ - 将应用程序转换为使用 dll。类 'std::map<_Kty,_Ty>' 需要有 dll 接口(interface)才能被类的客户端使用

c++ - 如何将用户输入作为参数传递给函数原型(prototype)?

c++ - 是否有 C++ 跨平台 USB 库?

c++ - 如何将整数值传递给 (const char *str) 函数参数?

c++ - 返回一个结构数组并在主类中使用

c++ - 用于自定义分辨率和同步计时的 AMD API 与 NVIDIA NVAPI 的 NDA 版本是什么等效的?

矩阵内的 C++ 正弦函数

C++ 为什么我不能将基类分配给子类?

c++ - 初始化 POD 结构的基类