I have been trying to overload the equal (==) and less than (<) operators for a linked sorted list. I am not sure if I u开发者_运维知识库nderstand exactly if what I am doing makes sense. I have a struct with a string variable for DestinationCity, of which these operators have to compare. I have used strcmp in an attempt to make it work. Here is the code:
bool sortedListClass::operator <(const flightRec& rhs) const{
if (strcmp(flightRec.DestinationCity, rhs.DestinationCity) < 0)
{ // I'm not sure if flightRec.DestionationCity is what I should write.
return true;
}
else
return false;
}
bool sortedListClass::operator ==(const flightRec& rhs) const{
if (strcmp(flightRec.DestinationCity, rhs.DestinationCity) == 0)
{
return true;
}
else
return false;
}
Here are the error messages.
sortedListClass.cpp: In member function ‘bool sortedListClass::operator<(const flightRec&) const’: sortedListClass.cpp:185:25: error: expected primary-expression before ‘.’ token
sortedListClass.cpp: In member function ‘bool sortedListClass::operator==(const flightRec&) const’: sortedListClass.cpp:194:28: error: expected primary-expression before ‘.’ token
// I'm not sure if flightRec.DestionationCity is what I should write.
You shouldn't:-). If you want to define operator<
on some class you do not do this in container class, but in the class which objects you want to compare. Here it would be flightRec
.
bool flightRec::operator< (const flightRec& other) {
// compare this and other
if (strcmp(this->DestinationCity, other.DestinationCity))
...
}
If you're still using std::string
, don't compare with strcmp
. ==
and <
are both defined on string
.
If you want to leave the 'struct' without members, you can define the binary operator as a non-member:
bool operator <(const flightRec& lhs, const flightRec& rhs)
{
if (strcmp(lhs.DestinationCity, rhs.DestinationCity) < 0)
return true;
else
return false;
}
精彩评论