将方法args放到我的班级时遇到问题:
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;
}
Run Code Online (Sandbox Code Playgroud)
问题,我得到一个C++编译器错误invalid vconversion from int to A::Mode,我不明白,为什么我不能连接到枚举值?我需要在代码中连接值,所以解决这个问题的任何帮助都会非常好.
Dan*_*rey 11
operator|默认情况下,两个枚举的结果不是枚举.课后,添加如下内容:
A::Mode operator|( A::Mode a, A::Mode b )
{
return A::Mode( int( a ) | int( b ) );
}
Run Code Online (Sandbox Code Playgroud)
如果您的标准库支持它,以下是更具前瞻性的证据,因为转换int并不总是正确的:
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 ) );
}
Run Code Online (Sandbox Code Playgroud)
与其他答案不同,您只需添加一次(到正确的位置),所有用途都会自动覆盖.