<分区>
重载否定运算符很简单:
bool MyClass::operator!() const
{
//return whatever comparison needs to be done
}
然后我可以写:
MyClass a;
if(!a)
{
//Do something
}
但我希望能够写:
if(a)
{
//Do something
}
我该怎么做?
<分区>
重载否定运算符很简单:
bool MyClass::operator!() const
{
//return whatever comparison needs to be done
}
然后我可以写:
MyClass a;
if(!a)
{
//Do something
}
但我希望能够写:
if(a)
{
//Do something
}
我该怎么做?
最佳答案
if 语句中的表达式将被转换为 bool。因此,您需要做的是让您的类可转换为 bool。这可以通过定义转换运算符来实现:
struct MyClass {
explicit operator bool() const {
return true;
}
};
完成此操作后,您不再需要 operator!
的重载,因为 bool 可以在转换后取反。
关于c++ - 重载否定运算符的反义词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56990620/