This question already has answers here:
Class member without a default constructor
                                
                                    (3个答案)
                                
                        
                                3年前关闭。
            
                    
我对C ++很陌生,并尝试编写简单的boost :: asio服务器包装器类,并且遇到了一些麻烦。按照此示例http://thisthread.blogspot.ru/2011/02/minimal-asio-tcp-server.html,并尝试将asio对象放入我的类的对象中,如下所示:

tcpserver.h:

class tcpserver {
public:
    tcpserver(unsigned short port  = 9999);
    ~tcpserver();

private:
    boost::asio::io_service io_service;
    boost::asio::ip::tcp::endpoint endpoint;
    boost::asio::ip::tcp::acceptor acceptor;
    boost::asio::ip::tcp::socket socket;
};

tcpserver.cpp:

#include "tcpserver.h"

tcpserver::tcpserver(unsigned short port){
    endpoint = boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v6(), port);
    acceptor = boost::asio::ip::tcp::acceptor(io_service, endpoint);
}


并且编译器引发以下错误:
/Users/rusik/huyorg/lib/tcpserver/tcpserver.cpp:3:12: error: constructor for 'tcpserver' must explicitly initialize the member 'acceptor' which does not have a default constructortcpserver::tcpserver(unsigned short port){

我应该如何正确地做到这一点?谢谢!

最佳答案

在初始化中使用它:

tcpserver::tcpserver(unsigned short port) :
    endpoint(boost::asio::ip::tcp::v6(), port),
    acceptor(io_service, endpoint)
}


因为当您按自己的方式进行操作时,临时会临时构造成员(对于acceptor来说是缺少的)。
在这里,它们是使用正确的参数直接构建的

10-07 16:29