重载与否定运算符相反

Overload the opposite of the negation operator?

本文关键字:运算符 重载      更新时间:2023-10-16

重载否定运算符很简单:

bool MyClass::operator!() const
{
    //return whatever comparison needs to be done
}

然后我可以写:

MyClass a;
if(!a)
{
    //Do something
}

但我希望能够写:

if(a)
{
    //Do something
}

我该怎么做?

if 语句中的表达式将转换为布尔值。因此,您需要做的是使您的类可转换为布尔值。这可以通过定义转换运算符来实现:

struct MyClass {
    explicit operator bool() const {
        return true;
    }
};

完成此操作后,您不再需要重载operator!因为转换后可以否定布尔值。