如何调用运算符内部的方法>如果调用的 methord 需要更改数据成员?

How to call a method inside the operator> method if the methord called needs to change data members?

本文关键字:调用 methord 如果 数据成员 何调用 运算符 方法 内部 gt      更新时间:2023-10-16

我构建了自己的minHeap,它要求我重载所有要推送到它的类的运算符。我有一个Region类,它有一个名为findSmallestCity的方法。该方法循环遍历道路对象(每个对象有两个城市),然后返回该区域内任何道路中最小的城市。

我的比较操作员需要知道两个地区中哪一个地区的指数城市较小(城市是整数值),因为如果两个地区的道路数量相同,它就决定了其中哪一个城市的指数较低。

以下是运营商和findSmallestCity:的代码

int Region::findSmallestCity(){
    curRoad = head;
    int smallestCity = curRoad->getCityA();
    while(curRoad != 0){
        if(curRoad->getCityA() <= smallestCity) smallestCity = curRoad->getCityA();
        if(curRoad->getCityB() <= smallestCity) smallestCity = curRoad->getCityB();
        curRoad = curRoad->nextRoad;
    }
    return smallestCity;
}
bool operator<( const Region &lhs, const Region &rhs)
{
    if(lhs.numRoads < rhs.numRoads) return 1;
    else if(lhs.findSmallestCity() < rhs.findSmallestCity()) return 1;
    else return 0;
}
bool operator>( const Region &lhs, const Region &rhs)
{
    if(lhs.numRoads > rhs.numRoads) return 1;
    else if(lhs.findSmallestCity() > rhs.findSmallestCity()) return 1;
    else return 0;
}
bool operator<=( const Region &lhs, const Region &rhs)
{
    if(lhs.numRoads < rhs.numRoads) return 1;
    else if(lhs.findSmallestCity() < rhs.findSmallestCity()) return 1;
    else return 0;
}
bool operator>=( const Region &lhs, const Region &rhs)
{
    if(lhs.numRoads > rhs.numRoads) return 1;
    else if(lhs.findSmallestCity() > rhs.findSmallestCity()) return 1;
    else return 0;
}

有没有一种方法可以绕过我得到的错误,比如:

error: passing ‘const Region’ as ‘this’ argument of ‘int Region::findSmallestCity()’ discards qualifiers [-fpermissive]|

只需使您的方法常量:

int Region::findSmallestCity() const { ... }

这使编译器知道您不打算更改Region,因此与constRegion对象一起使用是安全的。