[英]Overloading < operator c++
我目前正試圖為一個我建立的存儲NFL戲劇的班級超過一個不足的操作員。 對於我的課程項目,我們將數據項插入到BST中。 我已經從我的班級中以這種方式重載了運算符:
friend bool operator< (const NFLData& lhs, const NFLData& rhs){
if((lhs.getOffenseTeam().compare(rhs.getOffenseTeam())) == 0 ){//They're equal, go left
return true;
}
else{
return false;
}
}
但是,在Visual Studio 2010中,lhs和rhs參數以紅色下划線標注,當我嘗試運行它時,我收到以下錯誤:
c:\project 4draft\nfldata.h(105): error C2228: left of '.compare' must have class/struct/union
c:\project 4draft\nfldata.h(105): error C2662: 'NFLData::getOffenseTeam' : cannot convert 'this' pointer from 'const NFLData' to 'NFLData &' Conversion loses qualifiers
我從函數中的兩個參數中刪除了const,它不再強調我的任何代碼,但是當我編譯時,它給了我這些錯誤:
\bst.h(82): error C2678: binary '<' : no operator found which takes a left-hand operand of type 'const NFLData' (or there is no acceptable conversion)
c:\project 4draft\nfldata.h(104): could be 'bool operator <(NFLData &,NFLData &)' [found using argument-dependent lookup]
while trying to match the argument list '(const NFLData, NFLData)'
c:\project 4draft\bst.h(79) : while compiling class template member function 'void BST<T>::insert(const T &,BST<T>::TreeNode *&) const'
with
[
T=NFLData
]
c:\project 4draft\test.cpp(35) : see reference to class template instantiation 'BST<T>' being compiled
with
[
T=NFLData
]
c:\project 4draft\bst.h(84): error C2679: binary '<' : no operator found which takes a right-hand operand of type 'const NFLData' (or there is no acceptable conversion)
1> c:\project 4draft\nfldata.h(104): could be 'bool operator <(NFLData &,NFLData &)' [found using argument-dependent lookup]
1> while trying to match the argument list '(NFLData, const NFLData)'
我試圖弄清楚為什么這不起作用,我的BST是模板化的。
對於錯誤C2662: getOffenseTeam()
需要標記為const
:
rettype_unclear getOffenseTeam() const {
}
因為你不能在const引用(你的lhs
和rhs
是)上調用非const方法。
對於錯誤C2228:確保getOffenseTeam()
返回的內容具有compare
方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.