Leo*_*onS 4 c++ sorting operators
我有一个重载<运算符的问题.我有这门课:
WordEntry.h:
class WordEntry
{
public:
WordEntry(string word);
~WordEntry();
bool operator<(const WordEntry otherWordEntry);
string getWord();
private:
string _word;
};
Run Code Online (Sandbox Code Playgroud)
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());
}
Run Code Online (Sandbox Code Playgroud)
当我在main.cpp中使用它时,一切都很好:
WordEntry w1("Der");
WordEntry w2("das");
if (w1.operator<(w2)) {
cout << "w1 > w2";
}
else
{
cout << "w2 > w1";
}
Run Code Online (Sandbox Code Playgroud)
但是,当我叫sort()上一个vector与WordEntry对象,我会得到错误信息
二进制表达式的操作数无效('const WordEntry'和'const WordEntry')
它指向stl_algo.h.
有谁知道这里发生了什么?
现在,参数<是const,但成员不是.这意味着<2个const WordEntry&对象之间的比较将失败,因为它无法绑定<.你需要创建成员和参数const
bool operator<(const WordEntry& otherWordEntry) const;
bool WordEntry::operator<(const WordEntry& otherWordEntry) const {
...
}
Run Code Online (Sandbox Code Playgroud)
注意:正如评论中指出的那样,您也应该WordEntry通过引用传递
| 归档时间: |
|
| 查看次数: |
2057 次 |
| 最近记录: |