1

我的代码中出现以下错误,我不确定为什么因为在 client.hpp 中声明了“socketfd”并在 client.cpp 中的构造函数中使用,但是当我稍后尝试使用它时,我得到了一个错误。

终端输出:

g++ client.cpp -o client.o -pthread -c -std=c++11
client.cpp: In function ‘void sendMessage(std::string)’:
client.cpp:37:23: error: ‘socketfd’ was not declared in this scope

客户端.hpp

#include <iostream>
#include <cstring>
#include <sys/socket.h>
#include <netdb.h>

class Client {

    public:
        Client();
        ~Client();
        void sendMessage(std::string);

    private:
        int status, socketfd;
        struct addrinfo host_info;
        struct addrinfo *host_info_list;

};

客户端.cpp

#include "client.hpp"


Client::Client() {
    memset(&host_info, 0, sizeof host_info);
    std::cout << "Setting up the structs..." << std::endl;
    host_info.ai_family = AF_UNSPEC;
    host_info.ai_socktype = SOCK_STREAM;
    status = getaddrinfo("192.168.1.3", "8888", &host_info, &host_info_list);
    if (status != 0) {
        std::cout << "getaddrinfo error " << gai_strerror(status);
    }

    std:: cout << "Creating a socket..." << std::endl;
    socketfd = socket(host_info_list->ai_family, host_info_list->ai_socktype, host_info_list->ai_protocol);
    if (socketfd == -1) {
        std::cout << "Socket Errror ";
    }
    std::cout << "Connecting..." << std::endl;
    status = connect(socketfd, host_info_list->ai_addr, host_info_list->ai_addrlen);
    if (status == -1) {
        std::cout << "Connect Error" << std::endl;
    }
    std::cout << "Successfully Connected" << std::endl;
}

Client::~Client() {

}

void sendMessage(std::string msg) {
    std::cout << "Sending Message: " << msg << std::endl;
    int len;
    ssize_t bytes_sent;
    len = strlen(msg.c_str());
    bytes_sent = send(socketfd, msg.c_str(), len, 0);
}

这是我做过的第一个 C++,我有点困惑为什么会出现这个错误。

4

2 回答 2

5

Client::之前失踪了sendMessage()

void Client::sendMessage(std::string msg) {
     ^^^^^^^^
于 2013-03-16T21:59:13.533 回答
4

的函数签名sendMessage不是成员函数的签名。尝试这个-:

  void Client::sendMessage(std::string msg) {
于 2013-03-16T21:59:24.830 回答