C++: Operator overload syntax error

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • DouggieC
    New Member
    • Feb 2006
    • 1

    #1

    C++: Operator overload syntax error

    Hi,

    I am attempting to overload the '<' operator in order to sort an array structure, but get a syntax error in Borland Builder5.
    Code as follows:

    Code:
    struct GroupTeamType
    {
       AnsiString Name;
       int Played;
       int Won;
       int Drawn;
       int Lost;
       int GoalsFor;
       int GoalsAgainst;
       int GoalDiff;
       int Points;
    };
    
    GroupTeamType Group[4];
    
    // This line gives 'Declaration syntax error
    bool operator <(const GroupTeamType &first, const GroupTeamType &second)
    {
       return first.Points < second.Points;
    }
    As far as I can see, this syntax matches several examples I have found on the Web. Any idea what I'm doing wrong?

    Thanks
    Doug
  • vpawizard
    New Member
    • Nov 2006
    • 66

    #2
    Unfortunately, the operator overloading function has to defined in a class.
    The calling object then uses it like any other member function.
    e.g.When u say a<b where a and b are objects, the operator function of class of object 'a' is called and 'b' becomes the parameter for that function.

    Comment

    • Banfa
      Recognized Expert Expert
      • Feb 2006
      • 9067

      #3
      Originally posted by vpawizard
      Unfortunately, the operator overloading function has to defined in a class.
      This statement is not true you can overload an operator using a global function like DouggieC has tried to.


      DouggieC

      the only problem I had compiling your code is that the type AnsiString was not defined on my system, when a changed the definition of GroupTeamType to use a string (from the STL) instead of AnsiString it compiled without error.

      If you have code that produces errors and you post asking for help with it then it is best to post the errors as well and indicate which lines of code they occured on.

      Comment

      Working...