简体   繁体   中英

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?

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM