Avatar ·

C++中错误“passing const xxx as 'this' argument discards qualifiers”:如何修复

你好!我是一名C++初学者,遇到了一个无法理解的错误。我尝试使用std::set来存储自定义对象,但编译器报错:
error: passing 'const MyClass' as 'this' argument of 'bool MyClass::operator<(const MyClass&)' discards qualifiers [-fpermissive]
这是我的代码:
#include <iostream>
#include <set>

class MyClass {
public:
    MyClass(int val) : value(val) {}

    bool operator<(const MyClass& other) {
        return this->value < other.value;
    }

    int getValue() const { return value; }

private:
    int value;
};

int main() {
    std::set<MyClass> mySet;
    mySet.insert(MyClass(10));
    mySet.insert(MyClass(5));
    
    for (const auto& elem : mySet) {
        std::cout << elem.getValue() << " ";
    }
    return 0;
}
错误出现在operator<的定义行。我听说