问题
For example, I have defined a class
class MyClass
{
....
};
which operator do I have to overload in order to do the if comparison with a MyClass
object?
eg:
MyClass cc;
if ( cc ) // compile error
{
//do some stuff
}
I tried with
bool operator == ( int value ) ; //guess the if () will call this
or
bool operator != ( int value ) ;
but both give me a compile error!
回答1:
You should provide a bool
conversion operator:
struct MyClass
{
explicit operator bool() const { return true; }
};
Here, an explicit
operator is used to prevent unwanted implicit conversions to other types, specifically numeric types. Note that this is only possible since C++11.
回答2:
operator bool()
is the one you want. It takes care of type conversion from your class to type bool
.
回答3:
You have to provide a conversion operator for bool
or for something convertible to bool
. If you have C++11, the best way is this:
class MyClass
{
public:
explicit operator bool () const {
...
}
};
If you don't have C++11 (or at least its support for explicit conversion operators), things get a bit more tricky (because an implicit conversion can kick you real painfully when you least expect it). See the safe bool idiom for more information on this.
回答4:
You could override operator bool()
, but according to your example, you might also consider creating simple method that will return bool
. Then its usage could for example look like this:
MyClass cc;
if (cc.isValid())
{
// do some stuff
}
which would be more straightforward and also easier to read in this case. Custom operators are great for many things, but don't force it. Sometimes it's better to just keep it simple :)
来源:https://stackoverflow.com/questions/15616779/which-operator-to-overload-in-order-to-use-my-class-in-an-if-statement