jeudi 24 octobre 2019

Which takes precedence, the free function operator==() or the member function operator==()?

When the free operator function and the member operator function are both defined, which one is used for comparison?

#include <iostream>

class A;
class B;

bool operator==(const A &a, const B &b){ return true; };

class A
{
  public:
      bool operator==( const B &rhs ){ return false; };
};

class B
{
};

int main( int argc, char **argv )
{
  A a;
  B b;
  if( a == b )
  { 
      std::cout << "a==b" << std::endl;
  }
};

I ran the code a couple times and it seems that the member operator wins out. Is this always the case?

Aucun commentaire:

Enregistrer un commentaire