枚举类中的运算符重载

时间:2019-08-30 02:04:07

标签: c++ operator-overloading inner-classes enum-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. “枚举类test :: Loc不是类或命名空间。”
  2. “不匹配'operator!'(操作符类型为'test :: Loc')”

1 个答案:

答案 0 :(得分:1)

您可以使用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

相关问题