c++ - 如何在 cpp 类中声明 zeromq 套接字
问题描述
我正在尝试使用 zmq 创建一个通用节点,该节点将形成一个动态计算图,但是在我的类中的 zmq 套接字的前向声明中出现错误。我想知道是否有人可以对此有所了解?该类的精简版是;
节点.hpp
/*
* node.hpp
*/
#ifndef NODE_
#define NODE_
#include <iostream>
#include "zmq.hpp"
class Node
{
private:
std::string name_;
std::ostream& log_;
zmq::context_t context_;
zmq::socket_t subscriber_;
zmq::socket_t publisher_;
public:
Node(std::ostream& log, std::string name);
void sendlog(std::string msg);
};
#endif // NODE_
节点.cpp
/*
* node.cpp
*/
#include <iostream>
#include <string>
#include "zmq.hpp"
#include "node.hpp"
Node::Node(std::ostream& log, std::string name):
log_(log),
name_(name)
{
sendlog(std::string("initialising ") + name_);
zmq::context_t context_(1);
zmq::socket_t subscriber_(context_, zmq::socket_type::sub);
zmq::socket_t publisher_(context_, zmq::socket_type::pub);
subscriber_.connect("ipc:///tmp/out.ipc");
publisher_.connect("ipc:///tmp/in.ipc");
sendlog(std::string("finished initialisation"));
}
void Node::sendlog(std::string msg)
{
this->log_ << msg << std::endl;
}
我从 g++ 得到的错误
g++ main.cpp node.cpp -lzmq
node.cpp: In constructor ‘Node::Node(std::ostream&, std::__cxx11::string)’:
node.cpp:12:15: error: no matching function for call to ‘zmq::socket_t::socket_t()’
name_(name)
但是,当我查看 zmq.hpp 时,我看到了
namespace zmq
{
class socket_t : public detail::socket_base
...
我假设我以某种方式错误地进行了声明?我不太精通 cpp,但我将其用作一个项目来重新开始,因此欢迎一般评论/文献参考。
解决方案
显示的代码有两个问题。首先与...
zmq::context_t context_(1);
zmq::socket_t subscriber_(context_, zmq::socket_type::sub);
zmq::socket_t publisher_(context_, zmq::socket_type::pub);
您正在创建隐藏同名成员变量的局部范围变量。其次,因为您没有显式初始化subscriber_
或publisher_
在 ctor 的初始化程序列表中,编译器将尝试使用对其默认构造函数的隐式调用。但是zmq::socket_t
没有默认构造函数,因此您会看到错误。
修复只是将context_
,subscriber_
和publisher_
成员的初始化移动到 ctor 的初始化列表中...
Node::Node(std::ostream& log, std::string name)
: log_(log)
, name_(name)
, context_(1)
, subscriber_(context_, zmq::socket_type::sub)
, publisher_(context_, zmq::socket_type::pub)
{
sendlog(std::string("initialising ") + name_);
subscriber_.connect("ipc:///tmp/out.ipc");
publisher_.connect("ipc:///tmp/in.ipc");
sendlog(std::string("finished initialisation"));
}
推荐阅读
- android - 代码在 android 中以 kotlin 文件或布局文件的编码(未知)形式显示
- r - 在 R studio 中使用 barlop
- c++ - 使用多个 g++ 版本构建项目
- python - Django 表单未保存到数据库
- python - Pandas - 展开 pandas 中的多个列并根据展开的列分配值
- android - 错误:包androidx.core.math 不存在Camera Flutter
- android - 考虑到它们都共享相同的应用程序这一事实,是否可以与附近的(蓝牙?)设备(手机和平板电脑)进行通信?
- mongodb - 更新数组中的元素后如何更新总字段?
- regex - 有没有办法在后面创建多个角色?
- sql-server - 即使对于非常大的记录表中的 10 条记录,选择查询也需要很长时间