I want to write a class that is compatible for std::set, so I overload the “less than” operator like this. It works.
bool Segment::SVertex::operator<(const SVertex &rhs) const
{
return id < rhs.id;
}
However, since I write Java more than C++, ‘rhs.id’ looks very uncomfortable to me. So I change it to ‘rhs.getId()’ where getId() is just a normal getter function:
long SVertex::getId(){return id;}
This turns out to be a compile time error: can’t convert “this” pointer from “const Segment::SVertex” to “Segment::SVertex &”
(note that my VS2008 is not English and I translated the error message, so the line above is not necessarily exact)
I only know that ‘&’ denotes passing by reference and ‘const’ forbids any changes. I don’t exactly understand what’s going on behind the scene.
the problem is your getter function isn’t exactly ‘normal’; your getter should be
Note the const at the end: it tells the compiler/users that this method does not modify the class’ internals. So, it’s possible to use it in your operator < which is also const.
Const member functions can only call other member functions if they are also const; Non-const member functions can call any.