考虑这段代码:
#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;
}
}
这给了我一个错误。这是完整的消息 https://bitbucket.org/snippets/Rockstar5645/Le4A48:
/usr/include/c++/7.2.0/bits/stl_function.h:在 'constexpr bool std::greater<_tp>::operator()(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”)
{ 返回 __x > __y; }
似乎是因为这里的这个函数没有const
预选赛:
bool operator > (const MyStruct& other) {
return (key > other.key);
}
如果我加上的话
bool operator > (const MyStruct& other) const {
return (key > other.key);
}
然后一切就又好了。为什么会这样呢?我对运算符重载不太熟悉,所以我只是将其放入内存中,我们需要添加const
但它为什么有效仍然很奇怪operator<
没有const
.