【问题标题】:What's the difference between the scope of a function and a class函数的作用域和类的作用域有什么区别
【发布时间】:2019-03-29 12:58:57
【问题描述】:

我使用ros 并尝试将订阅者和服务器的定义放入外部函数中。然后回调没有运行。 spin() 函数不起作用。但是我经常看到其他人将服务器的定义放入一个类中,并且回调会起作用。那么这两个场景有什么区别呢?

这会起作用

int main(int argc, char **argv) 
{

  ros::init(argc, argv, "cood_tran");
  ros::NodeHandle nh;

    std::cout << "coodTran" << std::endl;
  target_obj = "None";
  ros::param::get("target", target_obj);

  ros::Subscriber ros_coord_pixel_sub =
  nh.subscribe("/darknet_ros/bounding_boxes", 1, darknetCallback);

  ros::Subscriber point_cloud_sub =
  nh.subscribe("camera/depth_registered/points", 1, pointCouldCallback);///camera/depth_registered/points  /camera/depth_registered/points<->color_optical

  ros::ServiceServer location_server =
  nh.advertiseService("location_srv", location);


  ros::spin();
  return 0;
}

这行不通

int main(int argc, char **argv) 
{

  ros::init(argc, argv, "cood_tran");
  ros::NodeHandle nh;

  coodTran(nh);


  ros::spin();
  return 0;
}

void coodTran(ros::NodeHandle nh)
{

  std::cout << "coodTran" << std::endl;
  target_obj = "None";
  ros::param::get("target", target_obj);

  ros::Subscriber ros_coord_pixel_sub =
  nh.subscribe("/darknet_ros/bounding_boxes", 1, darknetCallback);

  ros::Subscriber point_cloud_sub =
  nh.subscribe("camera/depth_registered/points", 1, pointCouldCallback);///camera/depth_registered/points  /camera/depth_registered/points<->color_optical

  ros::ServiceServer location_server =
  nh.advertiseService("location_srv", location);

}

这将起作用:

#include <darknet_ros/YoloObjectDetector.hpp>
#include <ros/ros.h>

int main(int argc, char** argv) {
  ros::init(argc, argv, "darknet_ros");
  ros::NodeHandle nodeHandle("~");

  darknet_ros::YoloObjectDetector yoloObjectDetector(nodeHandle);

  ros::spin();
  return 0;
}

【问题讨论】:

  • 我不明白这个问题。函数和类的范围没有任何共同之处。我能看到的唯一联系是您在两者中都声明了东西,并且它们由花括号分隔。我也看不到显示的代码与所问问题之间的联系。

标签: c++ function class


【解决方案1】:

在第二个片段中,您按值传递 NodeHandle。因此,在 coodTran 中,您正在更改原始 nh 的副本。 尝试像这样通过引用传递它:

    void coodTran(ros::NodeHandle& nh) {
       nh.sunscribe();
    }

或者传递指向原始对象的指针:

    void coodTran(ros::NodeHandle* nh) {
       nh->sunscribe();
    }

或者在函数中创建节点并返回句柄:

    ros::NodeHandle coodTran() {
        ros::NodeHandle nh;
        nh->sunscribe();
        return nh;
    }

【讨论】:

  • 它不起作用。我想原因可能是subscribe的定义在main函数之外。
  • 什么不完全有效?我的意思是,您尝试过哪种变体,它是如何失败的?
猜你喜欢
  • 1970-01-01
  • 2012-05-02
  • 2013-04-17
  • 1970-01-01
  • 2011-05-09
  • 1970-01-01
  • 2023-04-08
  • 2014-03-20
  • 2019-03-26
相关资源
最近更新 更多