Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ operator< overloading struct

struct player
{
    string name;
    int a;
    int v;
    int s;
    bool operator< (const player lhs, const player rhs)
    {
        if ((lhs.a < rhs.a)
            || ((lhs.a == rhs.a) && (lhs.v < rhs.v))
            || ((lhs.a == rhs.a) && (lhs.v == rhs.v) && (lhs.s > rhs.s))
            || ((lhs.a == rhs.a) && (lhs.v == rhs.v) && (lhs.s == rhs.s) && (lhs.name < rhs.name))
            )
            return true;
        else
            return false;
    }
};

I have this struct and I wish to make operator overloading for the operator <, but I keep getting the error "too many parameters for this operator function". can any one help me with that?

like image 226
Said A. Sryheni Avatar asked Oct 30 '25 19:10

Said A. Sryheni


2 Answers

If you define the operator within your struct you would do

bool operator<(const player& rhs) const
{
    // do your comparison
}

You would compare rhs.a to this->a (and each of the other variables)

like image 152
Cory Kramer Avatar answered Nov 02 '25 10:11

Cory Kramer


Yes, you should have only one parameter: the rhs parameter. Since you're defining operator< as a member function (aka method), you get the left operand for free via this.

So you should write it like this:

bool operator<(const player& rhs) const
{
    //Your code using this-> to access the info for the left operand
}

If you had instead defined the operator as a stand-alone function, then you would have needed to include parameters for both operands.

like image 45
Sildoreth Avatar answered Nov 02 '25 08:11

Sildoreth