Tabrock
Tabrock

Reputation: 1169

Overloading < operator c++

I'm currently trying to overload a less than operator for a class I've build that stores NFL Plays. For my class project, we're inserting data items into a BST. I've overloaded the operator in this way from within my class:

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;
    }
}

However, the lhs and rhs parameters are underlined in red in Visual Studio 2010, and when I try to run it it, I get these errors:

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

I removed const from both of the parameters in the function, it no longer underlines any of my code, however when I got to compile, it gives me these errors:

\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)'

I'm trying to figure out why this isn't working, my BST is templated.

Upvotes: 0

Views: 211

Answers (1)

Adam
Adam

Reputation: 17339

For error C2662: getOffenseTeam() needs to be marked const:

rettype_unclear getOffenseTeam() const {
}

because you cannot call a non-const method on a const reference (which your lhs and rhs are).

For error C2228: make sure that whatever getOffenseTeam() returns has a compare method.

Upvotes: 2

Related Questions