2013-03-16 85 views
1

我在代碼中收到以下錯誤,並且我不確定爲什麼'socketfd'在client.hpp中聲明並在構造函數中使用client.cpp,但後來當我嘗試並在稍後使用它時出現錯誤。C 11錯誤:在此範圍內未聲明'X'

端子輸出:

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++我已經做了,我有點困惑,爲什麼我得到這個錯誤。

回答

5

你錯過Client::sendMessage()

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

sendMessage函數簽名是不是一個成員函數。試試這個::

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