I have a simple class which is a concrete class and is not designed to be inherited. Also I want to be able to say !myobject where myobject is an instance of this class. I've already define operator bool()
. Should I also define bool operator!()
?
Here is trivial example of the class:
class Test
{
public:
...
explicit operator bool() {
return error_ == 0;
}
bool operator!() {
return error_ != 0;
}
private:
int error_;
};
I tried it as !myobject
and it works independent of !()
operator is being defined or not.
Looks like it is a silly question, but I couldn't find an answer for it.
CodePudding user response:
According to the C 17 Standard (8.3.1 Unary operators)
9 The operand of the logical negation operator ! is contextually converted to bool (Clause 7); its value is true if the converted operand is false and false otherwise. The type of the result is bool.
So there is no need to overload the operator !() when there is the conversion operator to the type bool.
CodePudding user response:
Use the operator bool() const in your class:
explicit operator bool() const {
return error_ == 0;
}
and no need to define overload !()
.