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

operator bool () 提供一个本类型到bool的隐式转换。

bool operator ==()可以分为bool operator ==( const T* 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

猜你喜欢

转载自blog.csdn.net/znzxc/article/details/80385995