gpt4 book ai didi

c++ - C 11 错误 : ‘X’ was not declared in this scope

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:27:14 29 4
gpt4 key购买 nike

我的代码中出现以下错误,我不确定为什么因为“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

客户端.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++,我有点困惑为什么会收到此错误。

最佳答案

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

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

关于c++ - C 11 错误 : ‘X’ was not declared in this scope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15455156/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com