为什么重载'运算符< '应该是上课的常量吗?

编程入门 行业动态 更新时间:2024-10-12 03:25:34
本文介绍了为什么重载'运算符< '应该是上课的常量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

有人可以在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对象还是sort是const方法?

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; '应该是上课的常量吗?

本文发布于:2023-11-06 03:51:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1562653.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:常量   应该是   运算符   lt   amp

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!