gpt4 book ai didi

c++ - 类中枚举类的运算符重载

转载 作者:行者123 更新时间:2023-11-28 04:11:21 25 4
gpt4 key购买 nike

我在嵌套类中使用私有(private)枚举类并想实现运算符!对于我的枚举类。

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

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 不是类或 namespace 。”。
  2. “与‘operator!’不匹配(操作数类型为‘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

关于c++ - 类中枚举类的运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57719632/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com