[英]How to access a public variable of subscriber class in the main function?
我想訪問我在訂閱者類中定義的listener::flow_message
(一個公共變量),在我的代碼的 main() 函數中。 在下面的代碼中,我只是簡單地打印了flow_message
參數來顯示問題。
我將flow_message
的訪問修飾符flow_message
為 private 和 protected 但它得到了編譯錯誤,我發現在主函數中訪問此變量的唯一方法是將其定義為 public。 我可以使用以下命令在 main 中獲取一些屬性,例如flow_message
向量的大小:
list.flow_message.size();
但是例如,當我想訪問flow_message
向量的第一個成員時,使用下面的命令我得到了分段錯誤錯誤。
list.flow_message[0];
// this is my code for subscribing the optical flow data
// using a class for subscriber callback function:
#include<ros/ros.h>
#include<opencv_apps/FlowArrayStamped.h>
#include<opencv_apps/FlowArray.h>
#include<opencv_apps/Flow.h>
#include<opencv_apps/Point2D.h>
#include<vector>
#include<numeric>
using namespace std;
class listener
{
public:
vector<opencv_apps::Flow> flow_message;
void callback(const opencv_apps::FlowArrayStamped::ConstPtr& msg);
};
void listener::callback(const opencv_apps::FlowArrayStamped::ConstPtr& msg)
{
listener::flow_message = msg->flow;
ROS_INFO("i got it");
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "dataman");
ros::NodeHandle n;
listener list;
ros::Subscriber sub = n.subscribe("/lk_flow/flows", 1, &listener::callback, &list);
while(ros::ok())
{
cout << "this is it: " << list.flow_message[0] << endl;
ros::spinOnce();
}
return 0;
}
正如我之前提到的,我的錯誤是在運行時:
Segmentation fault (core dumped)
感謝您的任何幫助或評論...
你去獲取flow_message[0]
但你永遠不會向向量中添加元素。 如果向量為空,則flow_message[0]
不存在。
太在向量中添加元素,你應該發布一條消息。
但是您還應該檢查向量中的元素:
while(ros::ok()) {
if (list.flow_message.empty()) {
std::cout << "no messages" << std::endl;
} else {
std::cout << "this is it: " << list.flow_message[0] << std::endl;
}
ros::spinOnce();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.