博客
关于我
在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中kill掉所有锁表的进程
查看>>
mysql中like % %模糊查询
查看>>
MySql中mvcc学习记录
查看>>
mysql中null和空字符串的区别与问题!
查看>>
MySQL中ON DUPLICATE KEY UPDATE的介绍与使用、批量更新、存在即更新不存在则插入
查看>>
MYSQL中TINYINT的取值范围
查看>>
MySQL中UPDATE语句的神奇技巧,让你操作数据库如虎添翼!
查看>>
Mysql中varchar类型数字排序不对踩坑记录
查看>>
MySQL中一条SQL语句到底是如何执行的呢?
查看>>
MySQL中你必须知道的10件事,1.5万字!
查看>>
MySQL中使用IN()查询到底走不走索引?
查看>>
Mysql中使用存储过程插入decimal和时间数据递增的模拟数据
查看>>
MySql中关于geometry类型的数据_空的时候如何插入处理_需用null_空字符串插入会报错_Cannot get geometry object from dat---MySql工作笔记003
查看>>
mysql中出现Incorrect DECIMAL value: '0' for column '' at row -1错误解决方案
查看>>
mysql中出现Unit mysql.service could not be found 的解决方法
查看>>
mysql中出现update-alternatives: 错误: 候选项路径 /etc/mysql/mysql.cnf 不存在 dpkg: 处理软件包 mysql-server-8.0的解决方法(全)
查看>>
Mysql中各类锁的机制图文详细解析(全)
查看>>
MySQL中地理位置数据扩展geometry的使用心得
查看>>
Mysql中存储引擎简介、修改、查询、选择
查看>>
Mysql中存储过程、存储函数、自定义函数、变量、流程控制语句、光标/游标、定义条件和处理程序的使用示例
查看>>