STL中rel_ops说明

关于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的解释,不知道理解有没有问题**

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值