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?
The
operator==can be implemented in two ways:thispointer implicitly to the function.Since you’re implementing
operator==forstd::pair, you cannot implement it as member function (ofstd::pair). The option you’re left with is non-member function.So implement it outside the class as:
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==forstd::pairwhich lexicographically compares the values in the pair, like I did above, i.e comparefirstwithfirstandsecondwithsecond. 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.