2013-11-05 105 views
0

我目前正在尝试为我构建的存储NFL Plays的类重载少于运算符。对于我的课程项目,我们将数据项插入BST。我重载这样的操作从我的类中:重载<operator C++

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 

我从无论是在功能的参数去掉常量,它不再强调我的任何代码,但是当我去编译,它给了我这些错误:

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

+1

请问您可以发布'NFLData'的定义吗?另外,因为如果两个字符串相同,“compare”将返回0,那么您的小于运算符实际上是否等于运算符? – templatetypedef

+1

你的一个函数不是'const'。 – 0x499602D2

+0

@templatetypedef我只是想弄清楚为什么它不会编译一个简单的案例,逻辑会有所不同后,我得到整理。我发布了类定义。 – TaylorTheDeveloper

回答

2

对于错误C2662:getOffenseTeam()需要被打上const

rettype_unclear getOffenseTeam() const { 
} 

,因为你不能调用一个const引用一个非const方法(您lhsrhs是)。

对于错误C2228: 请确保无论getOffenseTeam()返回的是否有compare方法。

+0

感谢亚当,这是常量。 – TaylorTheDeveloper