函数不能嵌套,那么如何在 C++ 中做到这一点? [关闭]

Posted

技术标签:

【中文标题】函数不能嵌套,那么如何在 C++ 中做到这一点? [关闭]【英文标题】:function cannot be nested then how to do this in C++? [closed] 【发布时间】:2012-10-11 17:56:58 【问题描述】:

这是我的程序

#define WIN32_LEAN_AND_MEAN
#include <stdlib.h>
#include <stdio.h>
#include <string.h> 
#include <process.h> 
#include<atlstr.h>
#include<Windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
using namespace std; 
#define DEFAULT_PORT "100"
 class Base

public     :    
    struct addrinfo    addr_;   
    unsigned short          port_;      
    CString                  hostname_;    
    CRITICAL_SECTION        sect_;       
    HANDLE                  threadHandle_;    
        HANDLE                  threadHandle1_;  
    bool                    connected_;

public  :       
    SOCKET          sock_; 
    A()
    

    


public:
    virtual int ConnectToMachine(void)=0;  //This will make socket connection with the machine.
    virtual int SendRequest(SOCKET sock)=0;      //This will send the request to the machine.
    virtual char* ReceiveResponse(SOCKET sock)=0;  //This will receive the response from the machine that is binary data.

static DWORD WINAPI ServerConnectThread(Base *my);
static UINT ThreadFunc(LPVOID param) ;
static  UINT receive();
static DWORD WINAPI startReceive(LPVOID param)
            Base *_this=(Base*)param;
            _this->receive();
            return 0;
        
;

 #define DEFAULT_BUFLEN 512
 class Derived :public Base

public:
int ConnectToMachine(void)
    
        int conResult,iResult;
        struct addrinfo           *result = NULL,*ptr = NULL;

        u_long iMode = 0;
        DWORD nTimeout = 5000; // 5 seconds
        int port=22;
        WSADATA wsaData;

        // Initialize Winsock

        iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
        if (iResult != 0) 
        
            printf("WSAStartup failed with error: %d\n", iResult);

        

        ZeroMemory( &addr_, sizeof(addr_) );
        addr_.ai_family = AF_UNSPEC;
        addr_.ai_socktype = SOCK_STREAM;
        addr_.ai_protocol = IPPROTO_TCP;

        // Resolve the server address and port
        conResult = getaddrinfo("192.168.1.7", DEFAULT_PORT, &addr_, &result);
        if ( conResult != 0 ) 
            printf("getaddrinfo failed with error: %d\n", conResult);
            WSACleanup();
            return 1;
        

        // Attempt to connect to an address until one succeeds
        for(ptr=result; ptr != NULL ;ptr=ptr->ai_next) 

            // Create a SOCKET for connecting to server
            sock_ = socket(ptr->ai_family, ptr->ai_socktype, 
                ptr->ai_protocol);
            if (sock_ == INVALID_SOCKET) 
                printf("socket failed with error: %ld\n", WSAGetLastError());
                WSACleanup();
                return 1;
            


            conResult = ioctlsocket(sock_, FIONBIO, &iMode);
            if (conResult != NO_ERROR)
                printf("ioctlsocket failed with error: %ld\n", conResult);



            conResult = setsockopt(sock_, SOL_SOCKET, SO_RCVTIMEO, (const char*)&nTimeout, sizeof(DWORD));
            if (conResult != NO_ERROR)
            
                printf("\nSetsocopt fail with error :%d\n",WSAGetLastError());

                return 0;
            


            // Connect to server.
            conResult = connect(sock_, ptr->ai_addr, (int)ptr->ai_addrlen);
            if (conResult == SOCKET_ERROR) 
                closesocket(sock_);
                sock_ = INVALID_SOCKET;
                continue;
            
            break;
        

        freeaddrinfo(result);

        if (sock_ == INVALID_SOCKET) 
            printf("Unable to connect to server!\n");
            WSACleanup();
            return 1;
        
        DWORD dwThreadId;

            threadHandle_=CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)ThreadFunc,this,0,&dwThreadId);


    

    int SendRequest(SOCKET sock)
    
        int sendResult;
        char data[6]="CM00";
        data[4]=0x0F;
        data[5]=0x0D;
        sendResult = send( sock, data, (int)strlen(data), 0 );
        if (sendResult == SOCKET_ERROR)
        
            printf("send failed with error: %d\n", WSAGetLastError());
            closesocket(sock);
            WSACleanup();
            return 1;
        

        printf("Bytes Sent: %ld\n",sendResult);
    



    char* ReceiveResponse(SOCKET sock )
    
        int recvResult;
        char recvBuf[1024];
        char common[138];
        int j;
        int w =0;
        int recvbuflen = DEFAULT_BUFLEN;

        do 


            recvResult = recv(sock, recvBuf, recvbuflen, 0);
            if ( recvResult > 0 )
               

                //wLog->WriteErrorLog(recvbuf);
                for(j=0;j<=recvResult;j++)
                
                    common[w] = recvBuf[j];
                    w++;

                

                printf("Bytes received: %d\n",recvResult);
                memset(recvBuf, 0, sizeof(recvBuf));

            
            else if ( recvResult == 0 )
                printf("Connection closed\n");
            else
                printf("recv failed with error: %d\n", WSAGetLastError());

         while( recvResult> 0 );

        return common;
    

    static UINT Derived::receive(void)
    
        while(1)
        
            SendRequest(sock_);
            ReceiveResponse(sock_);
            Sleep(10000);
        
    

    DWORD WINAPI Base::ServerConnectThread(LPVOID lpdwThreadParam)
    
        SOCKET ThreadSocket = INVALID_SOCKET;
        ThreadSocket=(SOCKET)lpdwThreadParam;
        while(1)
        
            SendRequest(ThreadSocket);
            ReceiveResponse(ThreadSocket);
            Sleep(10000);
        

    
     static UINT ThreadFunc(LPVOID param)    
         Base* obj = (Base*)param;   

         obj->ServerConnectThread(); //how to pass socket
      
;

我必须将我在连接函数中创建的套接字传递给服务器连接线程,你能指导我怎么做吗

【问题讨论】:

您可以将各种数据(可能包括指向函数的指针和指向其他数据的指针)打包到 struct 中,并将指向它的指针传递给创建原语的线程(例如 Posix 上的 pthread_create,或者在某些 Windows 系统上可能是 CreateThread)。 这里没有人会读到那个。请发布一个 minimal 完整示例来解释您的问题。不要发布大量与手头问题无关的代码。 @BasileStarynkevitch 你能不能给一些伪代码 @Harry:你能不能发一个小例子,读一些关于 C++ 编程的好书? 【参考方案1】:

TL;DR

使用成员变量:

class Base

    ...
public:
    int the_socket_that_i_created_in_connect_function;
;

【讨论】:

我相信他是通过(正确地)指出类定义 can 嵌套在C++。所以,如果你想嵌套一个函数,只需将它放在一个包装类中。

以上是关于函数不能嵌套,那么如何在 C++ 中做到这一点? [关闭]的主要内容,如果未能解决你的问题,请参考以下文章

如果我不能做到这一点,那么定义自己的对象有啥大智慧?

如何在 PL/pgSQL 中创建嵌套函数?

React - 如何映射嵌套对象值?

如何在C语言里实现“面向对象编程”

按第一项对嵌套列表进行排序——itemgetter 没有做到这一点

如何从函数返回向量引用?