枚举只能通过正确的引用传递

问题描述

我想请人解释一下为什么枚举只能通过正确的引用而不是简单的引用来传递?

 namespace n1
{
    enum e1
    {
        f = 1,f1
    };
}
void f(n1::e1&& e)
{
    std::cout<<static_cast<int>(e);

}
int main()
{
   f(n1::e1::f1);
    return 0;
}

解决方法

enum是常量,因此不能将其视为n1::e1&,而不能将其视为const n1::e1&

void f(const n1::e1& e) {
    std::cout<<static_cast<int>(e);
}
,

枚举是整数常量

  • 函数的枚举参数必须恒定

备注:您无需强制枚举即可显示其值


void f(const n1::e1& e) {
    std::cout<< e ;
}