C++运算符<重载

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()上一个vectorWordEntry对象,我会得到错误信息

二进制表达式的操作数无效('const WordEntry'和'const WordEntry')

它指向stl_algo.h.

有谁知道这里发生了什么?

Jar*_*Par 7

现在,参数<是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通过引用传递

  • 通过引用传递也是一个好主意. (2认同)