首页 > 解决方案 > 如何在 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,但我将其用作一个项目来重新开始,因此欢迎一般评论/文献参考。

标签: c++classzeromqforward-declaration

解决方案


显示的代码有两个问题。首先与...

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"));
}

推荐阅读