C++ 重载运算符链表 ADT

标签 c++ operator-overloading 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: 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/

相关文章:

c++ - 销毁并重新创建对象是否会使指向该对象的所有指针都无效?

c++ - qemu-系统-i386 : Error loading uncompressed kernel without PVH ELF Note

c++ - 使用系统 DBus 的 registerService 失败(但适用于 session DBus)

c++ - C++ 中的辅助运算符问题

android - 有没有办法让ADT项目目录布局更灵活?

c++ - 如何防止控制台窗口超出屏幕?

rust - 我可以在 Rust 中将 const 与重载运算符一起使用吗?

C++ - 重载 [] 运算符

java - Android ADT 无法运行项目

android - 更新到 ADT 20 后导出 Android 项目时出现 Proguard 错误