簡體   English   中英

如何在 cpp 類中聲明 zeromq 套接字

[英]How to declare a zeromq socket in a cpp class

我正在嘗試使用 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_ ,編譯器將嘗試使用對其默認構造函數的隱式調用。 但是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"));
}

以下兩個(私有)成員是通過默認(零參數)構造函數創建的:

zmq::socket_t subscriber_; zmq::socket_t publisher_;

但是,該構造函數不可用。 如果要將其存儲為成員,則需要一個指針並通過new對其進行初始化或在構造函數的初始化列表中對其進行初始化。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM