C ++ Boost ASIO套接字错误

时间:2016-10-10 14:44:05

标签: c++ sockets c++11 boost cmake

我今天刚刚在新的Linux环境中安装了CLion,我决定尝试创建一个简单的套接字服务器。我最终想用C ++创建一个套接字服务器(因为我已经用C#,Java,Python,PHP,Node.js ...)。

我收到了以下代码:

//
// Created by josh on 10-10-16.
//

#ifndef RANDOMPROGRAM_TEST_H
#define RANDOMPROGRAM_TEST_H

#include <iostream>
#include <boost/bind.hpp>
#include <boost/asio.hpp>

using namespace boost::asio::ip;

class test {

private:
    boost::asio::io_service io_service;
    tcp::acceptor acceptor;
    tcp::socket socket;

    test() {
        this->acceptor = tcp::acceptor(this->io_service, tcp::endpoint(tcp::v4(), 30000));

        this->socket = tcp::socket(io_service);

        acceptor.async_accept(this->socket, boost::bind(&this->handle_accept, this, this->socket, NULL));
    }

    void handle_accept(tcp::socket* client, const boost::system::error_code& error) {

    }
};
#endif //RANDOMPROGRAM_TEST_H

在我的主.cpp文件中(在程序执行时调用):

#include "test.h"

int main() {
    test t();
    return 0;
}

最后,我的CMakeLists.txt

cmake_minimum_required(VERSION 3.6)
project(Randomshitprogram)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

find_package(Boost 1.62.0 COMPONENTS system filesystem REQUIRED)

if(Boost_FOUND)

    message(STATUS "Boost_INCLUDE_DIRS: ${Boost_INCLUDE_DIRS}")
    message(STATUS "Boost_LIBRARIES: ${Boost_LIBRARIES}")
    message(STATUS "Boost_VERSION: ${Boost_VERSION}")

    include_directories(${Boost_INCLUDE_DIRS})

endif()

set(SOURCE_FILES main.cpp test.h)
add_executable(Randomshitprogram ${SOURCE_FILES})

现在,当我尝试执行该程序时,它会出现以下错误,并可能出现大量错误:

No matching function for call to ‘boost::asio::basic_socket_acceptor<boost::asio::ip::tcp>::basic_socket_acceptor()’

日志:

http://pastebin.com/a09FvuTk

1 个答案:

答案 0 :(得分:3)

  

当我尝试执行

你的意思是编译,对吗?这是编译错误,而不是运行时错误。

  

No matching function for call to 'boost::asio::basic_socket_acceptor<boost::asio::ip::tcp>::basic_socket_acceptor()'

此处记录了boost::asio::basic_socket_acceptor的构造函数。没有默认构造函数,这是编译器告诉你的。

您在此处调用(或尝试)默认构造函数:

test() /* here */ {
    this->acceptor = tcp::acceptor(this->io_service, tcp::endpoint(tcp::v4(), 30000));

    this->socket = tcp::socket(io_service);

    acceptor.async_accept(this->socket, boost::bind(&this->handle_accept, this, this->socket, NULL));
}

没有初始化列表。 test的所有数据成员必须在构造函数的主体之前构造

你的构造函数应该看起来像这样:

test()
: acceptor(io_service, tcp::endpoint(tcp::v4(), 30000))
, socket(io_service)
{
    acceptor.async_accept(socket, boost::bind(&this->handle_accept, this, this->socket, NULL));
}