Rome_Leader
Rome_Leader

Reputation: 2700

Operator Overloading (==)

I'm having some difficulty with this. I've determined I need to overload this operator for my personal project. It is necessitated by the use of the following line:

if(playerVec[i] == 0)

The player class has several data members for calculating one particular data member, mInitiative. This is the one I want to check in my if condition. Here is my attempt at overloading it:

bool operator==(const Player& lhs) const {
    return mInitiative == lhs.mInitiative;
}

It seems fine enough, but the error persists. If I want to compare that particular player datum to an integer (in this case, 0), how do I go about it? What's the mistake in my approach?

EDIT: I have tried:

 bool operator==(const Player& lhs, int rhs) const {
    //...
 }

But the compiler says there are too many parameters for the function. Why is this? Shouldn't == be able to take two?

Thanks!

Upvotes: 1

Views: 249

Answers (2)

keelar
keelar

Reputation: 6026

When trying to overload equality operator (i.e. ==), you always need to think about whether the target instances are really the same.

In your case, I think people might be confused when reading the following code if you provide the Player to integer comparison. Since it looks like checking whether a pointer is null or not:

if(playerVec[i] == 0)

Rather than overloading == operator of Player to compare with integer, I would suggest providing a get() function, which allows you to compare Player with integer more clearly. For example:

if (playerVec[i].getPlayerID() == 0)

If you will use some stl function to manage your Player vector (eg. sorting), then you can overload == or > operator for two Player instances.

Upvotes: 3

riv
riv

Reputation: 7323

There are two ways to overload an equality operator: declare it as a member, taking one argument (rhs); or declare it as a global, taking two arguments (lhs and rhs). Since your lhs is a Player, and your rhs is an integer, here are the two ways to define it:

// declared inside Player class as a member
bool operator == (int rhs) const
{
    return mInitiative == rhs;
}

// can also be declared inside Player class, but is not a member due to friend keyword
friend bool operator == (Player const& lhs, int rhs)
{
    return lhs.mInitiative == rhs;
}

That is leaving aside the style considerations of overloading operators in such a way.

Upvotes: 4

Related Questions