[英]C++ overloaded operator linked sorted list ADT
我一直在尝试为链接排序列表重载等于(==)和小于(<)运算符。 我不确定我是否确切地知道我在做什么。 我有一个带有DestinationCity的字符串变量的结构,这些运算符必须与之进行比较。 我使用strcmp试图使其工作。 这是代码:
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;
}
这是错误消息。
sortedListClass.cpp:在成员函数'bool sortedListClass :: operator <(const flightRec&)const'中:sortedListClass.cpp:185:25:错误:预期在'之前的主表达式。 代币
sortedListClass.cpp:在成员函数'bool sortedListClass :: operator ==(const flightRec&)const'中:sortedListClass.cpp:194:28:错误:预期的主表达式位于'之前。 代币
//我不确定FlightRec.DestionationCity是否应该写。
您不应该:-)。 如果要在某个类上定义operator<
,则不要在容器类中执行此操作,而是在要比较哪些对象的类中执行此操作。 在这里是flightRec
。
bool flightRec::operator< (const flightRec& other) {
// compare this and other
if (strcmp(this->DestinationCity, other.DestinationCity))
...
}
如果您仍在使用std::string
,请不要与strcmp
进行比较。 ==
和<
都在string
定义。
如果要使“结构”不包含成员,则可以将二进制运算符定义为非成员:
bool operator <(const flightRec& lhs, const flightRec& rhs)
{
if (strcmp(lhs.DestinationCity, rhs.DestinationCity) < 0)
return true;
else
return false;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.