1

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;
}
1
  • Why not make it use references and dereference the pointers for comparison? ie. if((*var1) > (*var2)) Commented Oct 12, 2011 at 1:44

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

3 Comments

It does not need to be a friend or a member any more than any other function would. It only needs to be a friend if it attempts to access private or protected members of S1.
Ahh, OK, thanks, @Mankarse. It's been a while since I did one of these that wasn't a member.
I'm not sure about Mankarse's answer, but this solution seems to be working for me. Thanks
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.