关系运算符重载的作用:可以让两个自定义类型对象进行对比操作。
代码实现关系运算符的重载:
#include <iostream>
using namespace std;
class Person
{
// friend const Person operator+(const Person &L, const Person &R);
private:
int a;
int b;
public:
//无参构造函数
Person()
{
}
//有参构造函数
Person(int a, int b):a(a),b(b)
{
}
//成员函数实现 > 号运算符重载
bool operator > (const Person &R)
{
if(a > R.a && b > R.b)
{
return true;
}
else
return false;
}
//成员函数实现 >= 号运算符重载
bool operator >= (const Person &R)
{
if(a >= R.a && b >= R.b)
{
return true;
}
else
return false;
}
//成员函数实现 < 号运算符重载
bool operator < (const Person &R)
{
if(a < R.a && b < R.b)
{
return true;
}
else
return false;
}
//成员函数实现 <= 号运算符重载
bool operator <= (const Person &R)
{
if(a <= R.a && b <= R.b)
{
return true;
}
else
return false;
}
//成员函数实现 == 号运算符重载
bool operator == (const Person &R)
{
if(a == R.a && b == R.b)
{
return true;
}
else
return false;
}
//成员函数实现 != 号运算符重载
bool operator != (const Person &R)
{
if(a != R.a && b != R.b)
{
return true;
}
else
return false;
}
};
int main()
{
Person p1(10,10);
Person p2(10,10);
if(p1 > p2)
{
cout << "p1 > p2" << endl;
}
else if(p1 >= p2)
{
cout << "p1 >= p2" << endl;
}
else if(p1 < p2)
{
cout << "p1 < p2" << endl;
}
else if(p1 <= p2)
{
cout << "p1 <= p2" << endl;
}
else if(p1 == p2)
{
cout << "p1 == p2" << endl;
}
else if(p1 != p2)
{
cout << "p1 == p2" << endl;
}
else
{
cout << "false" << endl;
}
return 0;
}