博客
关于我
在ROS中使用c++类
阅读量:495 次
发布时间:2019-03-07

本文共 6576 字,大约阅读时间需要 21 分钟。

一般做法:

1:在头文件中定义类:
定义类的所有成员函数的原型。
定义私有和公共数据成员。
定义类构造函数原型。
2:定义cpp文件:
包含上面的头文件。
包含已声明成员函数的工作代码。
包含在构造函数中封装必要的初始化代码。

例如.h文件

// example_ros_class.h header file //// wsn; Feb, 2015// include this file in "example_ros_class.cpp"// here's a good trick--should always do this with header files:// create a unique mnemonic for this header file, so it will get included if needed,// but will not get included multiple times#ifndef EXAMPLE_ROS_CLASS_H_#define EXAMPLE_ROS_CLASS_H_//some generically useful stuff to include...#include 
#include
#include
#include
#include
//ALWAYS need to include this//message types used in this example code; include more message types, as needed#include
#include
#include
// uses the "Trigger.srv" message defined in ROS// define a class, including a constructor, member variables and member functionsclass ExampleRosClass{ public: ExampleRosClass(ros::NodeHandle* nodehandle); //"main" will need to instantiate a ROS nodehandle, then pass it to the constructor // may choose to define public methods or public variables, if desiredprivate: // put private member data here; "private" data will only be available to member functions of this class; ros::NodeHandle nh_; // we will need this, to pass between "main" and constructor // some objects to support subscriber, service, and publisher ros::Subscriber minimal_subscriber_; //these will be set up within the class constructor, hiding these ugly details ros::ServiceServer minimal_service_; ros::Publisher minimal_publisher_; double val_from_subscriber_; //example member variable: better than using globals; convenient way to pass data from a subscriber to other member functions double val_to_remember_; // member variables will retain their values even as callbacks come and go // member methods as well: void initializeSubscribers(); // we will define some helper methods to encapsulate the gory details of initializing subscribers, publishers and services void initializePublishers(); void initializeServices(); void subscriberCallback(const std_msgs::Float32& message_holder); //prototype for callback of example subscriber //prototype for callback for example service bool serviceCallback(std_srvs::TriggerRequest& request, std_srvs::TriggerResponse& response);}; // note: a class definition requires a semicolon at the end of the definition#endif // this closes the header-include trick...ALWAYS need one of these to match #ifndef

//.cpp文件

#include "example_ros_class.h"//CONSTRUCTOR:  this will get called whenever an instance of this class is created// want to put all dirty work of initializations here// odd syntax: have to pass nodehandle pointer into constructor for constructor to build subscribers, etcExampleRosClass::ExampleRosClass(ros::NodeHandle* nodehandle):nh_(*nodehandle){    // constructor    ROS_INFO("in class constructor of ExampleRosClass");    initializeSubscribers(); // package up the messy work of creating subscribers; do this overhead in constructor    initializePublishers();    initializeServices();        //initialize variables here, as needed    val_to_remember_=0.0;         // can also do tests/waits to make sure all required services, topics, etc are alive}//member helper function to set up subscribers;// note odd syntax: &ExampleRosClass::subscriberCallback is a pointer to a member function of ExampleRosClass// "this" keyword is required, to refer to the current instance of ExampleRosClassvoid ExampleRosClass::initializeSubscribers(){       ROS_INFO("Initializing Subscribers");    minimal_subscriber_ = nh_.subscribe("example_class_input_topic", 1, &ExampleRosClass::subscriberCallback,this);      // add more subscribers here, as needed}//member helper function to set up services:// similar syntax to subscriber, required for setting up services outside of "main()"void ExampleRosClass::initializeServices(){       ROS_INFO("Initializing Services");    minimal_service_ = nh_.advertiseService("example_minimal_service",                                                   &ExampleRosClass::serviceCallback,                                                   this);      // add more services here, as needed}//member helper function to set up publishers;void ExampleRosClass::initializePublishers(){       ROS_INFO("Initializing Publishers");    minimal_publisher_ = nh_.advertise
("example_class_output_topic", 1, true); //add more publishers, as needed // note: COULD make minimal_publisher_ a public member function, if want to use it within "main()"}// a simple callback function, used by the example subscriber.// note, though, use of member variables and access to minimal_publisher_ (which is a member method)void ExampleRosClass::subscriberCallback(const std_msgs::Float32& message_holder) { // the real work is done in this callback function // it wakes up every time a new message is published on "exampleMinimalSubTopic" val_from_subscriber_ = message_holder.data; // copy the received data into member variable, so ALL member funcs of ExampleRosClass can access it ROS_INFO("myCallback activated: received value %f",val_from_subscriber_); std_msgs::Float32 output_msg; val_to_remember_ += val_from_subscriber_; //can use a member variable to store values between calls; add incoming value each callback output_msg.data= val_to_remember_; // demo use of publisher--since publisher object is a member function minimal_publisher_.publish(output_msg); //output the current value of val_to_remember_ }//member function implementation for a service callback functionbool ExampleRosClass::serviceCallback(std_srvs::TriggerRequest& request, std_srvs::TriggerResponse& response) { ROS_INFO("service callback activated"); response.success = true; // boring, but valid response info response.message = "here is a response string"; return true;}int main(int argc, char** argv) { // ROS set-ups: ros::init(argc, argv, "exampleRosClass"); //node name ros::NodeHandle nh; // create a node handle; need to pass this to the class constructor ROS_INFO("main: instantiating an object of type ExampleRosClass"); ExampleRosClass exampleRosClass(&nh); //instantiate an ExampleRosClass object and pass in pointer to nodehandle for constructor to use ROS_INFO("main: going into spin; let the callbacks do all the work"); ros::spin(); return 0;}

//测试

在终端分别输入 rosservice call example_minimal_service

请求服务。

在终端发布话题

rostopic pub -r 2 example_class_input_topic stm_msgs/Float32 2.0

结果显示

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

转载地址:http://pvkcz.baihongyu.com/

你可能感兴趣的文章
MySQL 添加索引,删除索引及其用法
查看>>
MySQL 用 limit 为什么会影响性能?
查看>>
MySQL 用 limit 为什么会影响性能?有什么优化方案?
查看>>
MySQL 用户权限管理:授权、撤销、密码更新和用户删除(图文解析)
查看>>
mysql 用户管理和权限设置
查看>>
MySQL 的 varchar 水真的太深了!
查看>>
mysql 的GROUP_CONCAT函数的使用(group_by 如何显示分组之前的数据)
查看>>
MySQL 的instr函数
查看>>
MySQL 的mysql_secure_installation安全脚本执行过程介绍
查看>>
MySQL 的Rename Table语句
查看>>
MySQL 的全局锁、表锁和行锁
查看>>
mysql 的存储引擎介绍
查看>>
MySQL 的存储引擎有哪些?为什么常用InnoDB?
查看>>
mysql 索引
查看>>
MySQL 索引失效的 15 种场景!
查看>>
MySQL 索引深入解析及优化策略
查看>>
MySQL 索引的面试题总结
查看>>
mysql 索引类型以及创建
查看>>
MySQL 索引连环问题,你能答对几个?
查看>>
Mysql 索引问题集锦
查看>>