有什么方法可以从 C++ 中的枚举 class 中随机获取?

Is there any way to get random from enum class in c++?

我想用枚举 class 中的随机元素填充一个变量。

所以我尝试将枚举 class 类型设置为 int 并将最后一个枚举从枚举 class 传递给 rand:

enum class Enumerator: int
{
    en1=0,
    en2,
    en3,
    ensCount
};

int main()
{
    srand(time(NULL));
    auto a=static_cast<Enumerator>(rand()%Enumerator::ensCount);
    return 0;
}

结果是 "no match for «operator%» (operand types are «int» and «Enumerator»)" 错误。

built-in模(%)运算符的操作数应该是整数或unscoped枚举类型.

Enumeratorscoped enumeration.

没有从范围枚举器的值到整数类型的隐式转换。
所以你必须使用static_cast来获取枚举器的数值。

int divisor = static_cast<int>(Enumerator::ensCount);
srand(time(NULL));
auto a = static_cast<Enumerator>(rand() % divisor);