0

我目前正在尝试为我构建的存储 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;
    }
}

但是,lhs 和 rhs 参数在 Visual Studio 2010 中带有红色下划线,当我尝试运行它时,出现以下错误:

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 是模板化的。

4

1 回答 1

2

对于错误 C2662:getOffenseTeam()需要标记const

rettype_unclear getOffenseTeam() const {
}

因为您不能在 const 引用(您的lhsandrhs是)上调用非常量方法。

对于错误 C2228:确保getOffenseTeam()返回的任何内容都有compare方法。

于 2013-11-05T01:21:51.470 回答