“枚举 - 从int”的无效转换在班上 [英] "enum - invalid conversion from int" in class

查看:97
本文介绍了“枚举 - 从int”的无效转换在班上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将方法args放在我的课上有问题:

I have a problem putting method args to my class:

class A {
  public:
    enum Mode {ModeA, ModeB, ModeC};

    ... // other methods, constructor etc

    void setMode(Mode m) {
      mMode = m;
    }

  private:
    Mode mMode;
}

int main(int argc, char **argv) {
  A a;
  a.setMode(A::ModeA | A::ModeC );

  return 0;
}

该问题,我得到一个C ++编译器错误无效vconversion从int到A :: Mode
我不明白,为什么我不能连接到枚举值?我需要在
代码中连接数值,所以任何帮助来解决这个问题将是非常好的。

The problem, I get a C++ compiler error invalid vconversion from int to A::Mode, I dont understand, why I can't concat to enum values? I need to concat values in my code, so any help to solve this would be very nice.

推荐答案

默认情况下,两个枚举的 operator | 的结果不是枚举。上课后,添加如下内容:

The result of operator| for two enums is not an enum by default. After your class, add something like this:

A::Mode operator|( A::Mode a, A::Mode b )
{
    return A::Mode( int( a ) | int( b ) );
}

如果您的标准库支持,以下是更多未来证明的转换到 int 并不总是正确的:

if your standard library supports it, the following is more future proof as the conversion to int is not always correct:

A::Mode operator|( A::Mode a, A::Mode b )
{
    typedef std::underlying_type< A::Mode >::type UL;
    return A::Mode( static_cast< UL >( a ) | static_cast< UL >( b ) );
}

与其他答案不同,您只需添加一次(到正确的地方)并自动覆盖所有用途。

Unlike the other answer, you just add this once (to the right place) and all uses are automatically covered.

这篇关于“枚举 - 从int”的无效转换在班上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆