C++ में "passing const xxx as 'this' argument discards qualifiers" त्रुटि: कैसे ठीक करें
नमस्ते! मैं एक शुरुआती C++ डेवलपर हूँ, और मुझे एक त्रुटि मिली है जिसे मैं समझ नहीं पा रहा हूँ। मैं std::set का उपयोग करके कस्टम objects को स्टोर करने की कोशिश कर रहा हूँ, लेकिन compiler यह त्रुटि दे रहा है:
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& obj : mySet) {
std::cout << obj.getValue() << std::endl;
}
return 0;
}
मैं समझ गया हूँ कि std::set elements को const रखता है, लेकिन मैं अपने operator< को const कैसे बनाऊँ? क्या कोई मेरी मदद कर सकता है?