比较 (struct &a, struct &b) 与 (const struct &a, const struct &b) 的 == 运算符

skp*_*o19 0 c++ struct constants comparator

Point在头文件中定义了一个结构类,如下所示 -

namespace global_planner {
    class GlobalPlanner : public nav_core::BaseGlobalPlanner {
        struct Point {
            __uint32_t x, y; 
            bool operator==(const Point &p1 ) {
                return ((p1.x == x) && (p1.y == y));  
            }
            bool operator<(const Point &p1 ) const {
                return ((p1.x < x) || (p1.x == x && p1.y < y) ) ; 
            }   
        };
    public:
        ///
    private: 
        ////               
    };
    
};
Run Code Online (Sandbox Code Playgroud)

在我的源文件(名为global_planner.cpp)中,我有一个名为的函数,generate_straight_path定义如下 -

bool GlobalPlanner::generate_straight_path(const Point &p1, const Point &p2){        
    if(costmap_ros_->getCost(p1.x, p1.y) == costmap_2d::LETHAL_OBSTACLE) {
        cout << "Point p1 is on obstacle!" << endl;
        return false;
    }
    if(costmap_ros_->getCost(p2.x, p2.y) == costmap_2d::LETHAL_OBSTACLE) {
        cout << "Point p2 is on obstacle!" << endl;
        return false;
    }
    if(p1 == p2) {return 1;}
    if(p1.x == p2.x){}
    if(p1.y == p2.y){}
  }
Run Code Online (Sandbox Code Playgroud)

当我编译 global_planner.cpp 时,出现以下错误 -

/home/skpro19/catkin_ws/src/my_global_planner/src/global_planner.cpp: In member function ‘bool global_planner::GlobalPlanner::generate_straight_path(const global_planner::GlobalPlanner::Point&, const global_planner::GlobalPlanner::Point&)’:
/home/skpro19/catkin_ws/src/my_global_planner/src/global_planner.cpp:150:11: error: no match for ‘operator==’ (operand types are ‘const global_planner::GlobalPlanner::Point’ and ‘const global_planner::GlobalPlanner::Point’)
     if(p1 == p2) {return 1;}
Run Code Online (Sandbox Code Playgroud)

如果我改变的定义错误消失generate_straight_path,从generate_straight_path(const Point &p1, const Point &p2)generate_straight_path(Point &p1, Point &p2)

为什么会这样?

lub*_*bgr 7

您的相等运算符重载是一个成员函数,但未标记为const

 bool operator==(const Point &p1 ) { return ((p1.x == x) && (p1.y == y)); }   
Run Code Online (Sandbox Code Playgroud)

当你把它变成一个const成员函数时,这应该按预期工作:

bool operator==(const Point &p1 ) const { return ((p1.x == x) && (p1.y == y)); } 
Run Code Online (Sandbox Code Playgroud)

通过运算符有点模糊,但是当您这样看时:

bool GlobalPlanner::generate_straight_path(const Point &p1, const Point &p2){
    // ...

    if (p1.operator==(p2)) /* ... */ ;
}
Run Code Online (Sandbox Code Playgroud)

这是调用成员运算符重载的更详细的方法,您可以看到这operator==一定是const因为函数参数const Point& p1const它本身。