c++ - 运算符 > 重载不起作用

标签 c++ oop c++11

之前我已经重载了operator <我已经对结构进行了排序。

现在我正在尝试重载 operator >但它不起作用(实际上甚至无法编译)。我需要一些帮助来找出查询。

#include <bits/stdc++.h>
#include <algorithm>
using namespace std;
struct a
{
    int num1;
    int num2;
    bool operator > (const a& rhs) const
    {
        return  num1>rhs.num1;
    }
};

int main()
{
    a array[1000];
    for(int i=0; i<2; i++)
    {
        cin>>array[i].num1>>array[i].num2;
    }
    sort(array, array+2);
    for(int i=0; i<2; i++)
    {
        cout<<array[i].num1<<" "<<array[i].num2<<endl;
    }
}

最佳答案

当查看 std::sort 时我们可以看到使用带有 2 个参数的重载时:

1) Elements are compared using operator<

这意味着如果您的自定义类型没有定义 operator<你会得到一个编译器错误。如果您不想重载此运算符,则可以使用自定义比较器作为第三个参数。或者,您可以反转 operator> 的结果:

bool operator < (const a& rhs) const
{
   return !(num1>rhs.num1);
}

关于c++ - 运算符 > 重载不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36981011/

相关文章:

c++ - 加载 BMP 时,biSizeImage 始终为 0

javascript - 重定义构造函数原型(prototype)后,对象构造函数指向原始构造函数而不是prototype.constructor

c# - 不是按名称而是按类型指定接口(interface)成员

c++ - 将新元素插入/放置到 unordered_map/unordered_set 时的提示

c++ - 当 KEY 为 boost::optional 参数时用于 boost 多索引的迭代器

c++ - 在 C++ 中拦截 sleep 调用

c++ - Boost::asio 和 boost::bind: Functor 内存永远不会被释放

c++ - Arduino Serial.available() 不断增加

c++ - DCOM 服务器调试

c++ - 模板类根据其他类的存在和优先级以及更多类型限制(如 const 和区分大小写)调用其他类的某些函数