为什么操作员需要常量,而操作员不需要常量? [英] Why is const required for 'operator>' but not for 'operator<'?

查看:182
本文介绍了为什么操作员需要常量,而操作员不需要常量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这段代码:

#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;

struct MyStruct
{
    int key;
    std::string stringValue;

    MyStruct(int k, const std::string& s) : key(k), stringValue(s) {}

    bool operator < (const MyStruct& other) {
        return (key < other.key);
    }
};

int main() {
    std::vector < MyStruct > vec;

    vec.push_back(MyStruct(2, "is"));
    vec.push_back(MyStruct(1, "this"));
    vec.push_back(MyStruct(4, "test"));
    vec.push_back(MyStruct(3, "a"));

    std::sort(vec.begin(), vec.end());

    for (const MyStruct& a : vec) {
        cout << a.key << ": " << a.stringValue << endl;
    }
}

它编译得很好,并给出了预期的输出。但如果我尝试按降序对结构进行排序:

#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;

struct MyStruct
{
    int key;
    std::string stringValue;

    MyStruct(int k, const std::string& s) : key(k), stringValue(s) {}

    bool operator > (const MyStruct& other) {
        return (key > other.key);
    }
};


int main() {
    std::vector < MyStruct > vec;

    vec.push_back(MyStruct(2, "is"));
    vec.push_back(MyStruct(1, "this"));
    vec.push_back(MyStruct(4, "test"));
    vec.push_back(MyStruct(3, "a"));

    std::sort(vec.begin(), vec.end(), greater<MyStruct>());

    for (const MyStruct& a : vec) {
        cout << a.key << ": " << a.stringValue << endl;
    }
}

这给了我一个错误。Here is the full message

实例化‘stexpr bool std::Greater<;_TP>::

/usr/include/c++/7.2.0/bits/stl_function.h:()(const_tp&;,const_tp&;)const[with_tp=MyStruct]::
/usr/include/c++/7.2.0/bits/stl_function.h:376:20:错误:不匹配‘OPERATOR>’(操作数类型为‘const MyStruct’和‘const MyStruct’)
{Return__x>__y;}

这似乎是因为此函数没有const限定符:

bool operator > (const MyStruct& other) {
        return (key > other.key);
}

如果我添加它,

bool operator > (const MyStruct& other) const {
        return (key > other.key);
}

然后一切又好起来了。为甚麽会这样呢?我不太熟悉运算符重载,所以我只是把它放在内存中,我们需要添加const,但仍然奇怪的是,为什么它在没有const的情况下适用于operator<

推荐答案

您会得到不同的行为,因为您实际上调用了两个不同的(重载)sort函数。

在第一种情况下,您调用两个参数std::sort,它直接使用operator<。由于向量元素的迭代器生成非常数引用,因此它可以很好地应用operator<

在第二种情况下,您使用的是std::sort的三个参数版本。接受函子的人。您通过了std::greater。并且该函数有一个声明如下的operator()

constexpr bool operator()( const T& lhs, const T& rhs ) const;

请注意常量引用。它绑定需要与常量引用进行比较的元素。因此您自己的operator>也必须始终正确。

如果您使用std::less调用std::sort,您的operator<将产生相同的错误,因为它不是常量正确的。

这篇关于为什么操作员需要常量,而操作员不需要常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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