我在重载 我有这门课:WordEntry.h:class WordEntry{public: WordEntry(string word); ~WordEntry(); bool operator<(const WordEntry otherWordEntry); string getWord();private: string _word;};WordEntry.cpp(我删除了构造函数和析构函数):string WordEntry::getWord(){ return _word;}bool WordEntry::operator<(WordEntry otherWordEntry){ return lexicographical_compare(_word.begin(),_word.end(),otherWordEntry.getWord().begin(),otherWordEntry.getWord().end());}当我像这样在 main.cpp 中使用它时,一切都很好: WordEntry w1("Der"); WordEntry w2("das"); if (w1.operator<(w2)) { cout << "w1 > w2"; } else { cout << "w2 > w1"; }但是当我使用 sort() 对象在 vector 上调用 WordEntry 时,我会收到错误消息 Invalid operands to binary expression ('const WordEntry' and 'const WordEntry')它指向 stl_algo.h 。有谁知道这里发生了什么? 最佳答案 现在 < 的参数是 const 但成员不是。这意味着两个 < 对象之间的 const WordEntry& 比较将失败,因为它无法绑定(bind)到 < 。您需要使成员和参数都 constbool operator<(const WordEntry& otherWordEntry) const;bool WordEntry::operator<(const WordEntry& otherWordEntry) const { ...}注意:正如评论中指出的,您还应该通过引用传递 WordEntry关于C++ 运算符 < 重载,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10234682/
10-12 22:58