现在的位置: 首页 > 综合 > 正文

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

2018年05月13日 ⁄ 综合 ⁄ 共 1074字 ⁄ 字号 评论关闭

需要实现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 false
global bool operator == ( bool &rhs,const MyClass &lhs )
test2 true
mmeber function:bool operator == ( const bool &rhs ) called
test3 false

抱歉!评论已关闭.