Transfer a pointer between the class

zhaozj2021-02-11  191

During the class, the class pointer is in the program, such as the CMYSocket class, there is an event such as OnRecEive, OnConnect, etc., you need to call other class members in the response. The CMYSocket class does not have other classes of pointers, so you need to pass other pointers.

Example: In the CMYDIALOG class, an instance cmydialog :: m_socket created in the CMYDIALOG class, and a member function mydialog :: OnRecEidData. Now you need to call myDialog :: OnRecEidData in the CMYSocket class, you will automatically Call myDialog :: OnRecEctionData.

Workaround: 1. Change CMYSocket constructor, CMYSOCKET :: CMYSocket (CMYDIALOG * MYDLG) 2. Add #include "mydialog.h" in the header file of CMYSocket. 3. Define a CMYSocket class in the CMYDIALOG class CMYSocket * M_csocket.4. Since the #include "mysocket.h" cannot be added in CMYDIALOG, it will cause the nested call of the two header files, so define an empty class CMYSocket with CMYSocket in CMYSocket; 5. in CMYDIALOG #include "cmysocket.h" is added to .CPP and initialize M_CSocket, m_csocket = new cmySocket (this). Here, NEW will call the CMYSocket constructor. Through these steps, you can successfully pass the CMYDIALOG's pointer to CMYSocket.

The code is as follows: ------------- MySocket.h ----------------- # include "mydialog.h" // Add to CMYDIALOG head File Class CMYSOCKET: PUBLIC CASYNCSOCKET {public: CMYSocket (CMYDIALOG * DLGWND); // Modify the constructor to incorporate the CMYDIALOG pointer. Virtual ~ csocket_rec ();}; ------------------------------------------------------------------------------------------------------------------------------------- -

------------- MyDialog.h -------------------------------------------------------------- CLASS CMYSOCKET; / / To prevent the nested calls of the class file, definition A Class CMYSocket class.

Class CMYDIALOG: PUBLIC CDIALOG {public: void onRecEidData (); private: cmysocket * m_psocket; // Define a CMYSocket type member variable} ---------------------------------------------------------------------------------------------------------- ----------------------

------------- MyDialog.cpp ----------------- # include "cmysocket.h" // Add to CMYSocket header file, make The following NEW will call the constructor of CMYSocket. Bool csocket_receivedlg :: OnNitdialog () {m_csocketrec = new csocket_rec (this); // This new will call the CMYSocket constructor.} ----------- -------------------------------- The above problem can also be solved by setting global variables, but from the perspective of the package. Look, this method is relatively better.

转载请注明原文地址:https://www.9cbs.com/read-5624.html

New Post(0)