关于operator bool () 和bool operator ==()

operator bool () 提供一个本类型到bool的隐式转换,不允许使用参数。

bool operator ==()可以分为bool operator ==( const bool& other),bool operator ==( const T& other),T代表类型。

即与bool类型的比较,和与本类的比较。

#include <iostream>
using namespace std;
class A
{
public:
    A(int a) :_a(a) {}
    operator bool()
    {
        cout << "operator bool" << endl;
	return _a;
    }
 
 private:
	 int _a;
 };
 int main()
 {
    A a(0);
    A b(10);
    if (a)
        cout << "a" << endl;
    if(a == b)
        cout<<"asdasddsa"<<endl; 
    getchar();
    return 0;
 }

运行结果如下:

operator bool
operator bool
operator bool

由此可见,在判断if(a == b)时,先把a、b分别转换为bool类型再进行判断。

这一次加上operator ==()

#include <iostream>
using namespace std;
class A
{
public:
    A(int a) :_a(a) {}
    operator bool()
    {
        cout << "operator bool" << endl;
	return _a;
    }
    bool operator==(const bool &other)
    {
        cout << "bool operator==(const bool &rhs)" << endl;
        return (bool)_a == other;
    }
    bool operator==(const A &other)
    {
        cout << " bool operator==(const A&other)" << endl;
        return this->_a == other._a;
    } 
private:    
    int _a; 
};
int main()
{    
    A a(0);
    A b(10);
    A c(10);
    if (a == true)
	    cout << "a == true" << endl;
    if (b == c)
	    cout << "b == c" << endl;
    getchar();
    return 0;
}

结果如下,

bool operator==(const bool &rhs)
bool operator==(const A&other)
b == c

 

 

 

 

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值