Overloading of the < operator
Nov 23, 2012 at 2:56pm UTC
Hi everyone. I'm dealing with those lines of code that does not compile:
1 2 3 4 5 6 7 8 9 10
bool operator < (const GlutSphere& first_sphere, const GlutSphere& second_sphere)
{
if (first_sphere->radius() < second_sphere->radius()) return true ;
else return false ;
}
bool operator > (const GlutSphere& first_sphere, const GlutSphere& second_sphere)
{
if (first_sphere->radius() > second_sphere->radius()) return true ;
else return false ;
}
Have you any idea of the reason why there's an error in that? Or maybe should I look at other parts of the code, because this one looks ok?
NOTE: the compiler says me that
bool operator <
and
bool operator >
must take exactly one argument.
Last edited on Nov 23, 2012 at 2:58pm UTC
Nov 23, 2012 at 2:59pm UTC
What error? On what line?
Nov 23, 2012 at 3:08pm UTC
Are your operators being declared within the declaration of class GlutSphere?
If so, as your operators are member functions of GlutSphere, you don't need the first of your arguments. The object instance takes its place.
1 2 3 4 5
bool operator < (const GlutSphere& other_sphere) const
{
if (radius() < other_sphere.radius()) return true ;
else return false ;
}
or equivalently, as the result of operator< is already true or false
1 2 3 4
bool operator < (const GlutSphere& other_sphere) const
{
return (radius() < other_sphere.radius());
}
Also note that as you're passing a reference to your GlutSphere, I would expect you would need to call radius using a . not ->, which is for pointers. If -> works then some evil overloading is going on somewhere.
Andy
Last edited on Nov 23, 2012 at 3:11pm UTC
Nov 23, 2012 at 3:41pm UTC
@hamsterman: sorry for having been very unclear in my first post, but I was very confused by the origin of the problem and how to formulate that. Thank you anyway.
@andywestken: ok, I've solved. Unfortunately I cannot modify the definition of
GlutSphere
so I can't overload the
< operator inside the definition of that class. So I've simply written in a part of my code
1 2 3 4
bool operator < (const GlutSphere& firstSphere, const GlutSphere& secondSphere)
{
return (firstSphere.radius() < secondSphere.radius());
}
I needed that in the use of the
std::sort
, and that sounds working ok. Thank you!
Nov 23, 2012 at 5:00pm UTC
If you need it for use with the std::sort alg, it's better to use a functor
1 2 3 4 5 6 7 8 9 10 11 12 13 14
class SortByRadius
{
public :
bool operator () (const GlutSphere& firstSphere, const GlutSphere& secondSphere) const
{
return (firstSphere.radius() < secondSphere.radius());
}
};
vector<GlutSphere> vec;
// etc
std::sort( vec.begin(), vec.end(), SortByRadius() );
Note that for C++11, you could use a lamda instead.
Andy
Last edited on Nov 23, 2012 at 5:03pm UTC
Topic archived. No new replies allowed.