Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;操作员<;超载_C++_Sorting_Operators - Fatal编程技术网

C++ C++;操作员<;超载

C++ C++;操作员<;超载,c++,sorting,operators,C++,Sorting,Operators,我对

我对<运算符的重载有问题。 我有这门课:

WordEntry.h:

class WordEntry
{
public:
    WordEntry(string word);
    ~WordEntry();

    bool operator<(const WordEntry otherWordEntry);

    string getWord();

private:
    string _word;
};
classwordentry
{
公众:
单词输入(字符串单词);
~WordEntry();

bool操作符现在
的参数对右值使用const引用,并使方法const向编译器保证不会更改对象

bool operator<(const WordEntry& otherWordEntry) const
{
    // comparison
}
因为您没有使用自定义比较谓词,所以可以只使用
std::string::operator
string WordEntry::getWord()

bool WordEntry::operator
const
copy几乎无法达到目的…@LeonS:请注意,您的代码仍然有未定义的行为。虽然它似乎可以工作,但如果您将一个字符串与子字符串进行比较,例如按正确的顺序(
WordEntry(“Hello”)比较“Hello”和“Hell”),您可能会发现应用程序有时会崩溃。operator
    WordEntry w1("Der");
    WordEntry w2("das");

    if (w1.operator<(w2)) {
       cout << "w1 > w2";
    }
    else 
    {
       cout << "w2 > w1";
    }
bool operator<(const WordEntry& otherWordEntry) const;

bool WordEntry::operator<(const WordEntry& otherWordEntry) const {
  ...
}
bool operator<(const WordEntry& otherWordEntry) const
{
    // comparison
}
if (w1 < w2) { // etc }
return _word < otherWordEntry._word;
const string& getWord() const { return _word; }
string WordEntry::getWord()
bool WordEntry::operator<(WordEntry otherWordEntry)
{
   return  lexicographical_compare(_word.begin(),
                                   _word.end(),
                                   otherWordEntry.getWord().begin(),
                                   otherWordEntry.getWord().end());
}