为什么重载'运算符< '应该是上课的常量吗? [英] Why overloaded ' operator < ' should be const for class?

查看:88
本文介绍了为什么重载'运算符< '应该是上课的常量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以在STL sort算法的上下文中解释此行为吗? 如果未定义operator < const,则会显示错误

Can anybody explain this behavior in context of STL sort algorithm? If operator < is not defined const it gives error,

error: passing ‘const B’ as ‘this’ argument of ‘bool B::operator<(const B&)’ discards qualifiers [-fpermissive] while (__pivot < *__last)

error: passing ‘const B’ as ‘this’ argument of ‘bool B::operator<(const B&)’ discards qualifiers [-fpermissive] while (__pivot < *__last)

sort是算法lss const对象还是sortconst方法?

Is sort algo lhs const object or sort is const method?

class B
{
 public:
    ...
    bool operator < (const B& b) const       // why const required here?
    {
        return (m_i < b.m_i);
    } 
    ...

 private:
    int m_i;
    int m_j;
};

int main()
{
  vector<B> Bvec2 {B(5), B(3), B(30), B(20), B(8)};
  std::sort(Bvec2.begin(), Bvec2.end());
  ...
}

推荐答案

将函数标记为const表示它不会更改对象.因此可以在const对象上使用.

Marking the function as const promises that it will not change the object. So it can be used on const objects.

STL几乎可以肯定地将参数作为const,因为这样做很聪明.

The STL almost certainly takes the arguments as const, because that is the smart thing to do.

operator<定义为const不会对您造成伤害,因为我无法想象拥有一个小于运算符来更改对象.那真是愚蠢.

It shouldn't hurt you to define operator< as const because I cannot imagine having a less-than operator that changes the object. That would just be silly.

如果您想确切地知道在Fedora 20机器上从libstdc ++ bits/stl_algo.h中复制出的一些代码在哪里:

If you want to know exactly where here is some code copied out of libstdc++ bits/stl_algo.h on a Fedora 20 machine:

  /// This is a helper function...
  template<typename _RandomAccessIterator, typename _Tp, typename _Compare>
    _RandomAccessIterator
    __unguarded_partition(_RandomAccessIterator __first,
                          _RandomAccessIterator __last,
                          const _Tp& __pivot, _Compare __comp)

const _Tp& __pivot,就在这里.

这篇关于为什么重载'运算符&lt; '应该是上课的常量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆