MrRoy
MrRoy

Reputation: 1183

Overload an operator taking pointers in parameter

I am trying to overload the '>' operator taking a pointer in parameter, however I get an error saying "operator > must have at least one parameter of type class". I do not get that error if I do not use pointer.

Note: S1 is a typedef'd structure, as well as elem.

bool operator>(S1 const *V1, S1 const *V2){
    if (V1->elem->code > V2->elem->code)
        return true;
    return false;
}

I use the operator in a case like this, for example :

S1 * funct(S1 *var1, S1 *var2){
    if (var1 > var2)
        return var1;
    return var2;
}

Upvotes: 1

Views: 207

Answers (3)

kovenzhang
kovenzhang

Reputation: 85

In my opinion, when you want to define a new operator which has more than one parameter.there are two things you must do.

  1. Overload operator must be defined outside of the class.
  2. The overload operator must be declared a friend functions or class of the class.

That's my experience.

Upvotes: 1

Mankarse
Mankarse

Reputation: 40603

This does not work because operator< is already defined for pointers. It is impossible to overload operators on built-in types because all of the operators that make sense for built-in types are already defined.

Upvotes: 2

kylben
kylben

Reputation: 349

The compiler will want to turn your example into comparing the two pointer values. Having one parameter as a class type will tell it what it needs to know to resolve the overload.

bool operator>(const S1& V1, const S1& V2){
    if (V1.elem->code > V2.elem->code)
        return true;
    return false;
}

S1 * funct(S1 *var1, S1 *var2){
    if (*var1 > *var2)
        return var1;
    return var2;
}

Also, and I'm a bit rusty on this, but I think you have to declare the operator as a friend of S1, or make it a memeber.

Upvotes: 1

Related Questions