[英]How can I overload a 'less than' operator in my C++ class in order to compare consts?
我試圖在我的類中重載小於運算符“<”,如下所示:
//header file
class HuffmanNode{
private:
...
...
int frequency;
public:
...
...
bool operator<(const HuffmanNode &rhs); //overload less than operator
};
//cpp file
bool HuffmanNode::operator<(const HuffmanNode &rhs){
return frequency < rhs.frequency;
}
我希望能夠按如下方式比較節點:
bool HuffmanTree::compareNode(const HuffmanNode &a, const HuffmanNode &b){
if (a < b){
return true;
}
else{
return false;
}
}
我遇到的問題是找到一種將兩個節點作為常量進行比較的方法。 我收到一條錯誤消息,說我的運算符重載方法需要標記為 const 但將標頭中的代碼更改為
const bool operator<(const HuffmanNode &rhs);
和cpp文件代碼
const bool HuffmanNode::operator<(const HuffmanNode &rhs){
return frequency < rhs.frequency;
}
似乎沒有消除錯誤。
我已經檢查了這個解決方案,但使用朋友關鍵字似乎也不起作用。
謝謝你的幫助!
您誤解了關鍵字const
的用法和定位概念。
只是為了澄清:
const T functionName(something);
意味着您的functionName
返回 T 類型的東西,這是一個常量。
現在這個:
T functionName(something) const;
意味着您的functionName
返回類型 T 並且該方法不會更改實例中的任何內容,即使使用聲明為const
的對象也可以安全使用它。
第二個選項是您正在尋找的選項。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.