博客
关于我
在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 学习总结(87)—— Mysql 执行计划(Explain)再总结
查看>>
Mysql 学习总结(88)—— Mysql 官方为什么不推荐用雪花 id 和 uuid 做 MySQL 主键
查看>>
Mysql 学习总结(89)—— Mysql 库表容量统计
查看>>
mysql 实现主从复制/主从同步
查看>>
mysql 审核_审核MySQL数据库上的登录
查看>>
mysql 导入 sql 文件时 ERROR 1046 (3D000) no database selected 错误的解决
查看>>
mysql 导入导出大文件
查看>>
MySQL 导出数据
查看>>
mysql 将null转代为0
查看>>
mysql 常用
查看>>
MySQL 常用列类型
查看>>
mysql 常用命令
查看>>
Mysql 常见ALTER TABLE操作
查看>>
MySQL 常见的 9 种优化方法
查看>>
MySQL 常见的开放性问题
查看>>
Mysql 常见错误
查看>>
mysql 常见问题
查看>>
MYSQL 幻读(Phantom Problem)不可重复读
查看>>
mysql 往字段后面加字符串
查看>>
mysql 快照读 幻读_innodb当前读 与 快照读 and rr级别是否真正避免了幻读
查看>>