[英]Operator overloading enum class
我正在嘗試重載enum類的&
運算符,但是我得到了這個編譯器錯誤:錯誤:'operator&='不匹配(操作數類型是'int'和'Numbers')。 有關於此的任何想法?
#include <iostream>
using namespace std;
enum class Numbers : int
{
zero = 0,
one = 0x01,
two = 0x02
};
inline int operator &(int a, Numbers b)
{
return ((a) & static_cast<int>(b));
}
int main() {
int a=1;
a&=Numbers::one;
cout << a ;
return 0;
}
編譯器正確地告訴了什么是錯的。 你沒有超載&=
。
盡管存在預期的語義, &=
不會自動擴展為a = a & Numbers::one;
如果你想同時擁有兩者,那么規范的方法是通常用op=
來實現op
。 所以您的原始功能調整如下:
inline int& operator &=(int& a, Numbers b)
{ // Note the pass by reference
return (a &= static_cast<int>(b));
}
新的使用它:
inline int operator &(int a, Numbers b)
{ // Note the pass by value
return (a &= b);
}
不錯的問題,但你非常有幫助的編譯器診斷告訴你需要知道的一切。
您缺少*按位AND賦值運算符“: operator&=
。
是的,你正在超載運營商&
。 但是你正在使用運算符&=
這是另一個運算符。 也超載,你會沒事的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.