如何调用运算符内部的方法>如果调用的 methord 需要更改数据成员?
How to call a method inside the operator> method if the methord called needs to change data members?
我构建了自己的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对象一起使用是安全的。
相关文章:
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 函数调用中参数的顺序重要吗
- OpenGL - 在抛出"__gnu_cxx::recursive_init_error"实例后终止调用?
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 在c++类上调用void函数
- 为什么 std::unique 不调用 std::sort?
- 调用专用模板时出错"no matching function for call to [...]"
- 选择要调用的构造函数
- C++为什么尽管我调用了void函数,它却不起作用
- 构造函数正在调用一个使用当前类类型的函数
- 变量没有改变?通过向量的函数调用
- 没有为自己的结构调用列表推回方法
- 调用'begin(int [n])'没有匹配函数
- 什么时候调用析构函数
- 如何用参数值调用函数(仅在运行时已知)
- std::cout.imbue()多重调用
- 如何调用运算符内部的方法>如果调用的 methord 需要更改数据成员?