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

发布时间:2024-12-12 10:43

关注生活质量,利于家庭关系和睦 #生活乐趣# #生活质量# #生活质量改善# #家庭和谐度#

最新推荐文章于 2024-09-02 23:15:15 发布

znzxc 于 2018-05-20 21:44:02 发布

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

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

网址:关于operator bool () 和bool operator ==() https://www.yuejiaxmz.com/news/view/451661

相关内容

深入学习ArduinoJson库 V6版本
关于double==0判断的优化
Vector容器重载运算符源码解析
C#中 Equals和= =的区别
OpenAI即将推出“Operator”智能体:自动化任务的新纪元
新AI助理来袭!OpenAI的Operator将如何改变你的生活?
OpenAI全新AI助理产品“Operator”即将发布,开启智能时代新篇章
家庭财务管理系统源代码
用PHP中的 == 运算符进行字符串比较
C++:揭秘哈希:提升查找效率的终极技巧

随便看看