我一直在尝试重载链接排序列表的等于 (==) 和小于 (<) 运算符。我不确定我是否完全理解我所做的是否有意义。我有一个带有 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: 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.
你不应该:-)。如果你想定义 operator<
在某些类上,您不在容器类中执行此操作,而是在您要比较的对象类中执行此操作。这里是flightRec
.
bool flightRec::operator< (const flightRec& other) {
// compare this and other
if (strcmp(this->DestinationCity, other.DestinationCity))
...
}
关于C++ 重载运算符链表 ADT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5453015/