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

需要实现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
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值