- operator bool () 提供一个本类型到bool的隐式转换,不允许使用参数。
- bool operator ==()有以下两种:
bool operator ==( const bool& other) --------与bool类型的比较
bool operator ==( const T& other),T代表类型。--------与本类的比较
1、operator 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类型再进行判断。
2、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