Overaload operator of a struct

Hey!

I'm wondering how to overload an operator in a struct.

struct TeamPoints{
string team_name;
int points;
};


What I wanted was to overload "<" and ">" to compare only points and not team_name.

Anyone can help?
Last edited on
1
2
3
4
bool operator<(const TeamPoints &a, const TeamPoints &b)
{
    return a.team_name < b.team_name;
}
Hey! thnks for helping..

I'm getting this error:

ld: duplicate symbol operator<(TeamPoints const&, TeamPoints const&)in ./Tournament.o and ./Season.o
collect2: ld returned 1 exit status
There should be a section in the tutorial on this website about operator overload.
Anyway you have seen the basics so just change the operator provided by kbw to:
1
2
3
4
bool operator<(const TeamPoints &a, const TeamPoints &b)
{
    return a.points < b.points;
}

Chances are the errors you are referring to are a result of the code that calls this operator. Could you post it?
Don't put the function definition in the header.
You could always inline it:

1
2
3
4
5
inline
bool operator<(const TeamPoints &a, const TeamPoints &b)
{
    return a.team_name < b.team_name;
}
When did headers get into this?
Duplicate function definitions are a common symptom of putting definitions in headers. Since OP appear to be a newbie, I inferred he did that.
it woeked with the inline
inline is probably right for this kind of trivial function, but normally you wouldn't put your function definitions in the header. You would put them in a separate file.
@Galik:

disagree. the header is the right place for the inline function. you can't put it in a .cpp
file and expect the function to be inlined in any translation unit other than that .cpp file
then.
I think what he meant is that most functions should not be inlined.
Last edited on
@helios

Absolutely right. I guess I was a little ambiguous there.
oh, ok. Comment withdrawn then.
Topic archived. No new replies allowed.