c11错误:' X '未在此范围内声明

C 11 error: ‘X’ was not declared in this scope

本文关键字:范围内 声明 错误 c11      更新时间:2023-10-16

我在我的代码中得到以下错误,我不确定为什么因为'socketfd'是在client.hpp中声明的,并且在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

client.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;
};

client.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++,我有点困惑为什么我得到这个错误。

您在sendMessage()之前缺少Client:::

void Client::sendMessage(std::string msg) {
     ^^^^^^^^

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

  void Client::sendMessage(std::string msg) {