c++ - 为什么重载的 ' operator < ' 应该是类的常量?

标签 c++ stl operator-overloading

谁能在 STL 的上下文中解释这种行为 sort算法? 如果operator <未定义 const它给出了错误,

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

sort算法 lhs const对象或 sortconst方法?

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 promise 它不会更改对象。所以它可以用在 const 对象上。

STL 几乎肯定会将参数作为 const,因为这是明智之举。

定义operator< 不会对您造成伤害作为 const 因为我无法想象有一个小于运算符来改变对象。那将是愚蠢的。

如果您想知道在 Fedora 20 机器上从 libstdc++ bits/STL_algo.h 复制的代码的确切位置:

  /// 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 , 就在那里。

关于c++ - 为什么重载的 ' operator < ' 应该是类的常量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23927003/

相关文章:

c++ - (错误 C2678)错误 : No operator "<<" matches these operands

c++ - 如何做到这一点?

c++ - 重载一个可以区分非静态成员方法和其他函数的模板函数

c++ - 当迭代器不是随机访问时,如何在映射结束之前停止迭代 "n"?

c++ - STL(标准模板库)中使用的设计模式

C++ 运算符重载不符合数学要求

python - 在 python 中的两个对象之间的操作中,其操作重载为优先级?

c++ - 未能包含 Boost 库

c++ - 编写简单的 STL 泛型函数的问题

c++ - 对于输入迭代器,为什么 a == b 并不意味着++a ==++b?