我对 < 运算符的重载有疑问。 我有这个类:
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";
}
但是当我在带有 WordEntry
对象的 vector
上调用 sort()
时,我会收到错误消息
Invalid operands to binary expression ('const WordEntry' and 'const WordEntry')
它指向STL_algo.h
。
有人知道这里发生了什么吗?
最佳答案
现在 <
的参数是 const 但成员不是。这意味着 <
2 const WordEntry&
之间的比较对象将失败,因为它无法绑定(bind)到 <
.您需要使成员和参数都成为 const
bool operator<(const WordEntry& otherWordEntry) const;
bool WordEntry::operator<(const WordEntry& otherWordEntry) const {
...
}
注意:正如评论中所指出的,您还应该传递 WordEntry
引用
关于C++ 运算符 < 重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10234682/