有关C++对象与bool比较时的操作符重载

来源:互联网 发布:兽血天龙网络连接 编辑:程序博客网 时间:2024/06/01 07:32

需要实现operator bool ()的重载。

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

如上:

写了一个完整的例子

#include <iostream>using namespace std;class MyClass{public:    MyClass(int value):mValue(value)    {    }    operator bool ()    {        cout << "mmeber function:operator bool() called "<<mValue<<endl;        return mValue;    }    bool operator == ( const bool &rhs )    {        cout << "mmeber function:bool operator == ( const bool &rhs ) called"<<endl;        return (bool)mValue == rhs;    }private:    int mValue;};bool operator == ( const MyClass &lhs, bool rhs ){    cout << "global bool operator ==( const MyClass &lhs, bool &rhs ) "<<endl;    return true;}bool operator == ( const bool &rhs,const MyClass &lhs ){    cout << "global bool operator == ( bool &rhs,const MyClass &lhs )"<<endl;    return true;}int main(){    MyClass c1(0);    MyClass c2(10);    if ( c1 )    {        cout << " test1 true "<<endl;    }    else    {        cout << " test1 false"<<endl;    }    //bool result = (true == c1);    if ( true == c1 )    {        cout << "test2 true"<<endl;    }    else    {        cout << "test2 false"<<endl;    }    if ( c2 == false )    {        cout << "test3 true"<<endl;    }    else    {        cout << "test3 false"<<endl;    }}


输出如下:
mmeber function:operator bool() called 0 test1 falseglobal bool operator == ( bool &rhs,const MyClass &lhs )test2 truemmeber function:bool operator == ( const bool &rhs ) calledtest3 false

原创粉丝点击