class 中枚举 class 的运算符重载

Operator overloading of enum class in class

我在嵌套 class 中使用私有枚举 class 并且想要实现运算符!对于我的枚举 class.

我知道怎么做。但是当我试图在嵌套 class 中控制枚举 class 的运算符时,编译器将我的运算符视为 class 的运算符,而不是枚举 class 的运算符。

class test{
    private:
        enum class Loc : bool{
            fwrd = true,
            bkrd = false
        };

        Loc Loc::operator!(){        //error msg 1.
             return Loc(!bool(*this));
        }

        Loc operator!(){
             return something;       //this treated as test's operator
        }


        Loc doSomething(Loc loc){
             return !loc;            //error msg 2.
        }


}

enum class Other : bool{
    fwrd = true,
    bkrd = false
};
Other operator!(Other o){                //this works
    return Other(!bool(*this));
}

错误消息

  1. "enum class test::Loc is not a class or a namespace.".
  2. "no match for ‘operator!’ (operand type is ‘test::Loc’)"

您可能会使用 friend 函数:

class test
{
private:

    enum class Loc : bool{
        fwrd = true,
        bkrd = false
    };
    friend Loc operator!(Loc loc){
         return Loc(!bool(loc));
    }
    Loc doSomething(Loc loc){
         return !loc;
    }
};

Demo