C++笔记之表驱动法-全局静态结构体变量的应用实例ColorMAP
code review!
代码
#include <ros/ros.h>
#include <visualization_msgs/Marker.h>
struct RGBA{
RGBA(){
red.r = 1; green.r = 0; blue.r = 0;
red.g = 0; green.g = 1; blue.g = 0;
red.b = 0; green.b = 0; blue.b = 1;
red.a = 1; green.a = 1; blue.a = 1;
ColorMAP={
{"red", red },
{"green", green},
{"blue", blue }
};
};
std_msgs::ColorRGBA red;
std_msgs::ColorRGBA green;
std_msgs::ColorRGBA blue;
std::map<std::string,std_msgs::ColorRGBA> ColorMAP;
};
static RGBA rgba;
int main(int argc, char** argv)
{
ros::init(argc, argv, "marker_publisher");
ros::NodeHandle nh;
ros::Publisher marker_pub = nh.advertise<visualization_msgs::Marker>("marker", 10);
// 创建第一个Marker
visualization_msgs::Marker marker1;
marker1.header.frame_id = "map";
marker1.header.stamp = ros::Time::now();
marker1.lifetime = ros::Duration(); // 设置持久化属性为false
marker1.ns = "marker1";
marker1.id = 1;
marker1.type = visualization_msgs::Marker::SPHERE;
marker1.pose.position.x = 1.0;
marker1.pose.position.y = 2.0;
marker1.pose.position.z = 0.0;
marker1.pose.orientation.w = 1.0;
marker1.scale.x = 0.5;
marker1.scale.y = 0.5;
marker1.scale.z = 0.5;
marker1.color = rgba.ColorMAP["red"];
// 创建第二个Marker
visualization_msgs::Marker marker2;
marker2.header.frame_id = "map";
marker2.header.stamp = ros::Time::now();
marker2.lifetime = ros::Duration(); // 设置持久化属性为false
marker2.ns = "marker2";
marker2.id = 2;
marker2.type = visualization_msgs::Marker::CUBE;
marker2.pose.position.x = -1.0;
marker2.pose.position.y = 2.0;
marker2.pose.position.z = 0.0;
marker2.pose.orientation.w = 1.0;
marker2.scale.x = 0.5;
marker2.scale.y = 0.5;
marker2.scale.z = 0.5;
marker2.color = rgba.ColorMAP["blue"];
ros::Rate rate(1); // 发布频率为1Hz
while (ros::ok()) {
// 发布单个Marker消息
marker_pub.publish(marker1);
marker_pub.publish(marker2);
ros::spinOnce();
rate.sleep();
}
return 0;
}
主要目的是创建一个包含RGB颜色信息的结构体,并在程序初始化时设置颜色的默认值,同时提供一个全局的rgba对象,以便在后续的代码中可以方便地访问和使用这些颜色信息。这有助于使代码更加模块化和易于维护,因为颜色信息被封装在一个结构体中,并且可以在整个程序中共享。