pyt*_*hon 2 c++ overwrite operator-keyword
例如,我已经定义了一个类
class MyClass
{
....
};
Run Code Online (Sandbox Code Playgroud)
为了与MyClass对象进行if比较,我必须重载哪个运算符?
例如:
MyClass cc;
if ( cc ) // compile error
{
//do some stuff
}
Run Code Online (Sandbox Code Playgroud)
我试过了
bool operator == ( int value ) ; //guess the if () will call this
Run Code Online (Sandbox Code Playgroud)
要么
bool operator != ( int value ) ;
Run Code Online (Sandbox Code Playgroud)
但两个都给我一个编译错误!
您应该提供bool转换运算符:
struct MyClass
{
explicit operator bool() const { return true; }
};
Run Code Online (Sandbox Code Playgroud)
这里,explicit运算符用于防止对其他类型(特别是数字类型)的不必要的隐式转换.请注意,这只能在C++ 11之后实现.