Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Overloading operator< for struct: Error too many parameters

For an assignment students have to make a Card struct that keeps the Suit, Rank and Bitmap of a Card. This struct needs an overloaded "<" operator to compare whether the lhs Card's Rank is smaller than the rhs Card and return the bool. So far this is my Card.h file:

#pragma once

#include "GameEngine.h"

struct Card
{

public:
//Constructor and Destructor
Card();
virtual ~Card();

//Methods
bool operator< (const Card& lhs, const Card& rhs)
{
    return (lhs.m_Rank < rhs.m_Rank);
}

//Enumerations
enum class Suit
{
    Diamonds,
    Clubs,
    Hearts,
    Spades,
};

enum class Rank
{
    RankAce,
    RankTwo,
    RankThree,
    RankFour,
    RankFive,
    RankSix,
    RankSeven,
    RankEight,
    RankNine,
    RankTen,
    RankJack,
    RankQueen,
    RankKing,
};

private:
//Datamembers
Bitmap *m_BmpPtr;
Rank m_Rank;
Suit m_Suit;
};

However the operator< overload claims that it has too many parameters. Isn't this the right way to make sure both lhs and rhs can be compared in one overload? It's not like I have to split it up right?

Many thanks in advance.

like image 725
Emvidasch Avatar asked Oct 19 '25 13:10

Emvidasch


1 Answers

The compiler think this is a member function, but member function operators cannot have more than one argument. The first argument is implicitly *this while the second is the one you supply.

You can make this a member function by stripping the first argument and using *this in place of lhs. Otherwise, you can use an idiomatic solution and make it a friend:

friend bool operator< (const Card& lhs, const Card& rhs)
{
    return lhs.m_Rank < rhs.m_Rank;
}
like image 78
David G Avatar answered Oct 21 '25 01:10

David G