博客
关于我
在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学习总结(78)——MySQL各版本差异整理
查看>>
Mysql学习总结(79)——MySQL常用函数总结
查看>>
Mysql学习总结(7)——MySql索引原理与使用大全
查看>>
Mysql学习总结(80)——统计数据库的总记录数和库中各个表的数据量
查看>>
Mysql学习总结(81)——为什么MySQL不推荐使用uuid或者雪花id作为主键?
查看>>
Mysql学习总结(82)——MySQL逻辑删除与数据库唯一性约束如何解决?
查看>>
Mysql学习总结(83)——常用的几种分布式锁:ZK分布式锁、Redis分布式锁、数据库分布式锁、基于JDK的分布式锁方案对比总结
查看>>
Mysql学习总结(84)—— Mysql的主从复制延迟问题总结
查看>>
Mysql学习总结(85)——开发人员最应该明白的数据库设计原则
查看>>
Mysql学习总结(8)——MySql基本查询、连接查询、子查询、正则表达查询讲解
查看>>
Mysql学习总结(9)——MySql视图原理讲解与使用大全
查看>>
Mysql学习笔记 - 在Centos7环境下离线安装Mysql
查看>>
MySQL学习笔记十七:复制特性
查看>>
Mysql学习第一课-mysql的定义及sql语句
查看>>
mysql安全模式: sql_safe_updates
查看>>
mysql安装,卸载,连接
查看>>
MySQL安装之没有配置向导
查看>>
mysql安装出现 conflicts with mysql*的解决办法
查看>>
mysql安装卡在最后一步解决方案(附带万能安装方案)
查看>>
mysql安装和启动命令小结
查看>>