C++ C++;操作员<;超载
我对<运算符的重载有问题。 我有这门课: WordEntry.h:C++ C++;操作员<;超载,c++,sorting,operators,C++,Sorting,Operators,我对
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::operatorstring WordEntry::getWord()
bool WordEntry::operatorconst
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());
}