我目前正在尝试为我构建的存储 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 4draftnfldata.h(105): error C2228: left of '.compare' must have class/struct/union
c:project 4draftnfldata.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 4draftnfldata.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 4draftbst.h(79) : while compiling class template member function 'void BST<T>::insert(const T &,BST<T>::TreeNode *&) const'
with
[
T=NFLData
]
c:project 4drafttest.cpp(35) : see reference to class template instantiation 'BST<T>' being compiled
with
[
T=NFLData
]
c:project 4draftbst.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 4draftnfldata.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
方法。