关于STL中rel_ops说明,相信大家已经在网上看到很多关于这个的解释和说明,但是很多只有一点说明,并未说明原因,本人水平实在不高,但愿意说说自己的看法,
>
http://www.cplusplus.com/reference/utility/rel_ops/,这是网站说明,其实平常不太看这个的,因为必须联网才能看,所以总是觉得不舒服,所以粘贴过来,
关系运算符
这个命名空间声明模板函数四个关系运算符(!=,>,<=和>=),从而产生的行为operator==(对!=)和operator<(对>,<=和>=):
namespace rel_ops {
template <class T> bool operator!= (const T& x, const T& y) { return !(x==y); }
template <class T> bool operator> (const T& x, const T& y) { return y<x; }
template <class T> bool operator<= (const T& x, const T& y) { return !(y<x); }
template <class T> bool operator>= (const T& x, const T& y) { return !(x<y); ``}
}
#include <iostream>
using namespace std;
class A
{
public:
int a;
int b;
A(const int c,const int d)
{
a = c;b = d;
}
bool operator<(const A& m)const
{
return a < m.a;
}
bool operator==(const A& m)const
{
return a == m.a;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
using namespace rel_ops;
A a(10,10);
A b(15,15);
cout << (a<b) << endl;
cout << (a>b) << endl;
cout << (a == b) << endl;
cout << (a != b) << endl;
while(1);
}
**这是简单例子,这个例子中:
1.类的里面并不局限于两个变量的比较,可以是三个,四个,关键看你要重载的意义是什么,
2.可以看到只需要重载 < 和 == ,就可以了,就可以使用 >=,<=,>,!=,四个运算符,,因为这四个运算符需要调用我们自己重写的< 和 ==,
3.为什么要加const,假如我们不加const重载<和==,那么我们在使用<和==运算符是没有问题,但是我们无法使用另外四个运算符,这是因为这四个运算符在STL里面是const类型的参数,如果我们重载<和==没有加const,那么另外四个运算符无法调用我们自己重载的<和==,所以会产生错误,所以为了保证另外四个运算符可以调用我们的重载函数,必须加const,
这个是关于rel_ops的解释,不知道理解有没有问题**