Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

operator== overloading considering non-static member function

I have defined a class like this

using namespace std;
class foo {
public:
  typedef std::pair< int, int > index;
  bool operator == ( const index &l, const index &r )
  {
    return (l.first == r.first && l.second == r.second);
  }
  void bar()
  {
    index i1;
    i1.first = 10;
    i1.second = 20;
    index i2;
    i2.first = 10;
    i2.second = 200;
    if (i1 == i2)
       cout << "equal\n";
  }
};

However I get this error in windows

error C2804: binary 'operator ==' has too many parameters

and this error in linux

operator==(const  std::pair<int, int>&, const std::pair<int, int>&)’ must take exactly one argument

I found this topic overloading operator== complaining of 'must take exactly one argument' and seems to be a problem with static and non-static functions in a class. However I don't know how to apply this

For example, this is not correct

  bool operator == ( const index &r )
  {
    return (this->first == r.first && this->second == r.second);
  }

How can I fix that?

like image 692
mahmood Avatar asked Dec 16 '22 15:12

mahmood


1 Answers

The operator== can be implemented in two ways:

  • As member function: in this case, the function takes one argument and is invoked on the left operand which is passed as this pointer implicitly to the function.
  • As non-member function, in which case, the function takes two arguments, left and right operands.

Since you're implementing operator== for std::pair, you cannot implement it as member function (of std::pair). The option you're left with is non-member function.

So implement it outside the class as:

bool operator==(std::pair<int,int> const & l, std::pair<int,int> const & r)
{
    return (l.first == r.first && l.second == r.second);
}

But then you don't really need to implement it yourself unless you want to implement it differently. The Standard Library has already provided a generic version of operator== for std::pair which lexicographically compares the values in the pair, like I did above, i.e compare first with first and second with second. If you need to compare them differently, only then provide your own specific definition (non-template version).

The above mentioned points are worth noting as to how to implement operator== when you need it for your defined types.

like image 138
Nawaz Avatar answered Feb 16 '23 00:02

Nawaz