我遇到了<运算符过载的问题。 我有这个类:
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()
时,会出现错误消息:
二进制表达式的操作数无效('const WordEntry'和'const WordEntry')
并且它指向stl_algo.h
。
有人知道这里发生了什么吗?
const
的复制基本上是毫无意义的... - AJG85