Refactoring basic ROS code into object-oriented one
I was trying to refactor the existing basic ROS talker code into somewhat that of using OO paradigm. By the way, I am not a good object-oriented programmer but willing to practice a lot and apply in any projects that I am involved. Here I provide the code and there are currently 2 problems I am having. They are:
- Problem with the PointCloud constructor. I got an error of "extra qualification ‘PointCloud::’ on member ‘PointCloud’".
- I'm confused the way I should use loop_rate().
Hopefully, someone who are very good in OO programming can help or improve this little thing..The code:
#include "ros/ros.h"
#include "std_msgs/String.h"
#include <sstream>
class PointCloud
{
private:
int count;
PointCloud();
ros::NodeHandle n;
ros::Publisher chatter_pub;
// ros::Rate loop_rate(int);
std_msgs::String msg;
std::stringstream ss;
public:
PointCloud::PointCloud()
{
chatter_pub = n.advertise<std_msgs::String>("chatter", 1000);
}
void display();
};
void PointCloud::display()
{
// loop_rate(10);
count = 0;
while (ros::ok())
{
ss << "hello world " << count;
msg.data = ss.str();
ROS_INFO("%s", msg.data.c_str());
chatter_pub.publish(msg);
ros::spinOnce();
// loop_rate.sleep();
++count;
}
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "talker");
PointCloud pointCloud;
ROS_INFO("Node started");
ros::spin();
ROS_INFO("Node finished");
return 0;
}
The modified code:
#include "ros/ros.h"
#include "std_msgs/String.h"
#include <sstream>
class PointCloud
{
private:
ros::NodeHandle n;
ros::Publisher chatter_pub;
int count;
public:
PointCloud();
void display();
};
PointCloud::PointCloud()
{
chatter_pub = n.advertise<std_msgs::String>("chatter", 1000);
count = 0;
}
void PointCloud::display()
{
std_msgs::String msg;
std::stringstream ss;
ss << "hello world " << count;
msg.data = ss.str();
ROS_INFO("%s", msg.data.c_str());
chatter_pub.publish(msg);
++count;
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "talker");
PointCloud pointCloud;
ROS_INFO("Node started");
ros::Rate loop_rate(10);
while (ros::ok())
{
ros::spinOnce();
pointCloud.display();
loop_rate.sleep();
}
ROS_INFO("Node finished");
return 0;
}