关于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

 

 

 

 

  • 19
    点赞
  • 54
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
bool operator==(CWParameter &p)是一个重载的关系运算符,用于比较CWParameter类型的对象是否相等。根据引用\[1\]中的说明,重载的关系运算符可以用于与bool类型和本类对象的比较。在这种情况下,它用于与另一个CWParameter对象进行比较。根据引用\[2\]中的示例,重载的关系运算符通常会返回一个bool类型的值,表示比较的结果。在这个例子中,重载的关系运算符可能会比较CWParameter对象的某些属性,例如gate和input_idx,以确定它们是否相等。请注意,根据引用\[3\]中的说明,如果重载的关系运算符是一个常成员函数,它将不能更改数据成员的值,也不能调用那些能引起数据成员值变化的成员函数,只能调用const成员函数。因此,bool operator==(CWParameter &p)可能是一个常成员函数,用于比较CWParameter对象的相等性。 #### 引用[.reference_title] - *1* *2* [bool operator==(const T& t) const,关系运算符重载](https://blog.csdn.net/weixin_42322256/article/details/124074546)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [bool operator==(const Array&)const; 这最后一个const 是做什么用的](https://blog.csdn.net/weixin_34327761/article/details/85818308)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值