Use MFC to serialize data and C ++ objects

Source: Internet
Author: User
Tags clear screen

Serialized data

--Example program: memo

Create a new single-document SDI application. Select cformview for the View class so that you can enter it in the window. Create three edit boxes on the page, and then add three corresponding edit box variables. These three variables are member variables of the View class. to exchange data, three corresponding variables must be created in the document class. Then, both the document class and View class should initialize the data members. In the document class, this work is usually done in the onnewdocument () function. This is because the onnewdocument () function of the document class is triggered when any of the following operations occurs:

  • When the user starts the application;
  • Select "new" from the "file" menu;

The oninitialupdate () function is usually responsible for the initialization of the View class. when any of the following operations occur, the Code triggers the oninitialupdate () function execution of the View class:

  • When the user starts the application;
  • Select "new" from the "file" menu;
  • Select the "open" option from the "file" menu;

The method for getting the document class pointer in the View class is cfoodoc * pdoc = gerdocument ();
With this document pointer, you can operate the document data: m_viewdata = pdoc-> m_docdata;

The serialized code is very simple. Ar is a Document Object (carchive object) corresponding to the selected file ):

// Cfoodoc serialize void cfoodoc: serialize (carchive & AR) {If (AR. isstoring () {// write data to the file ar <m_docdata;} else {// read data from the file ar> m_docdata ;}}

In this way, the data is written to the file. Select "save" or "Save as" in the "file" menu to complete data serialization. If no data is saved, you are prompted to save the modified data when you exit the program. For details, see the source code.

Serializing C ++ objects

--Example program: PHN

Create a new single-document SDI application. Select cformview for the View class so that you can enter it in a window.

Declare a C ++ class to be serialized. Such as cphone;

Processing of document classes:
Declare an MFC coblist class object in the document class. This class is very useful and has powerful functions. It can be used to easily maintain the list of C ++ objects, for example, adding or deleting list elements. Make the following declaration in the header file of the document class:

CObList m_PhoneList;

The preceding Declaration can be of the Public type, so that other classes can directly access it. You can also use the private type to declare a public access function, such as getphonelist (). This function can return the m_phonelist address.

Generally, data can be initialized in the onnewdocument () function of the document class;

// Create a CPhone ObjectCPhone* pPhone = new CPhone();pPhone->m_Name = "";pPhone->m_Phone = "";// Add new object to the m_PhoneList listm_PhoneList.AddHead(pPhone);

The initialization of the member variables in the cphone class is not required because the cphone constructor has completed this task. The addhead () function adds the newly created cphone object to the m_phonelist list. Therefore, whenever you create a new document (such as starting an application), an empty cphone object will be added to the m_phonelist list. Note that the member function addhead () of the coblist class adds an object to the "Header" of the list (the beginning of the list), so the parameter is the address of the object to be added.

Delete the content in the m_phonelist list

M_phonelist is maintained in the memory, so it must be maintained at any time. As long as any of the following three events occurs, you must delete the objects in the m_phonelist list from the memory:

  • The user exits the application;
  • The user starts a new document, for example, selecting the "new" option from the "file" menu;
  • Open an existing document. For example, select the open option from the File menu;

Declare the delete operation function in the header file of the document class:

virtual void DeleteContents();

The implementation is as follows:

// Delete all items in the list and release the memory occupied by the List objects while (! M_phonelist.isempty () {Delete m_phonelist.removehead ();}

View class processing:

Declare the data member of the View class:

Position m_position; // The current position coblist * m_plist in the document class list; // The list pointing to the document class

Initialize the data member of the View class in the oninitialupdate () function.

Position m_position; coblist * m_plist; // get the document class pointer cfoodoc * pdoc = (cfoodoc *) getdocument (); // obtain the URL m_phonelist of the document class m_plist = & (pdoc-> m_phonelist); // obtain the header position m_position = m_plist-> getheadposition (); // update the View data member cphone * pPhone = (cphone *) m_plist-> getat (m_position); m_name = pPhone-> m_name; m_phone = pPhone-> m_phone; // use the new data member variable value to update the screen to display updatedata (false); // control the input focus (cdialog *) This) -> gotodlgctrl (getdlgitem (idc_name ));

Update document data

When you modify the data member of the View class, that is, when you modify the content in the form editing box, the data member of the document class will be modified after the code is executed.

Void cfooview: onenchangename () {// use the screen input to update the control variable updatedata (true); // get the document pointer cfoodoc * pdoc = (cfoodoc *) getdocument (); // update the document cphone * pPhone = (cphone *) m_plist-> getat (m_position); pPhone-> m_name = m_name; // set the flag to truepdoc-> setmodifiedflag ();}

Move the record in the list and modify the corresponding functions in the View class.

// Declare a temporary position variable position temp_pos; // use the current list position to update temp_postemp_pos = m_position; // update temp_pos m_plist-> getprev (temp_pos) with the previous/or later position; if (temp_pos = NULL) {// no previous elementmessagebox (_ T ("bottom of file encountered! "), _ T (" phone for Windows ");} else {// update the view Member Data m_position = temp_pos with the previous record in the list; cphone * pPhone = (cphone *) m_plist-> getat (m_position); m_name = pPhone-> m_name; m_phone = pPhone-> m_phone; updatedata (false );} // control the input focus (cdialog *) This)-> gotodlgctrl (getdlgitem (idc_name ));

Add and delete list records:

// Add record // clear screen input control m_name = ""; m_phone = ""; updatedata (false ); // create a new cphone object cphone * pPhone = new cphone (); pPhone-> m_name = m_name; pPhone-> m_phone = m_phone; // Add a new object to the end of the list and update m_position = m_plist-> addtail (pPhone) with a new position. // obtain the document pointer cfoodoc * pdoc = (cfoodoc *) getdocument (); // set the modification flag to truepdoc-> setmodifiedflag (); // control the input focus (cdialog *) This) -> gotodlgctrl (this-> getdlgitem (idc_name); // Delete the record // save the old pointer cobject * pold before deleting; pold = m_plist-> getat (m_position ); // Delete the m_plist-> removeat (m_position) element from the list; // Delete pold from the memory; // if the list has been cleared, add an empty record if (m_plist-> isempty () {onbnclickedaddbutton ();} // obtain the document pointer cphndoc * pdoc = (cphndoc *) getdocument (); // set the modification flag to truepdoc-> setmodifiedflag (); // display the first record oninitialupdate () in the list ();

Serialize Processing

We need to serialize the cphone object and write the C ++ object to a file. Therefore, we need to add the corresponding serial code to the definition and implementation file of the cphone class, first, add an MFC macro to the cphone header file. This is the macro required for serialization. You must provide it with a parameter, that is, the class name.

// Serialize the macro definition declare_serial (cphone)

The second is to declare a serialized function. This prototype is required. to serialize the cphone Object List, the cphone class must have its own serialize () function:

// Serialize () virtual void serialize (carchive & AR );

The corresponding code must be added to the cphone implementation file. This macro is another macro required for serialization. It has three parameters: Class Name and base class name, the third is the application version number, which can be defined as any value. When serializing data to a file, this version number must also be written to the file.

// Serialize the macro to implement implement_serial (cphone, cobject, 0 );

Serialize () Implementation

if (ar.IsStoring()){ ar << m_Name << m_Phone;}else{ ar >> m_Name >> m_Phone;}

Note that to use the coblist class member function serialize (), the following prerequisites must be met:

  • The list object must be a derived class Object of the MFC cobject class, that is, the cphone class must be a derived class of the cobject class;
  • The object class in the list must have a constructor without parameters. If needed, you can also have other constructors with parameters;
  • The serialize () function of the List class must be declared and implemented, that is, cphone: serialize ();
  • The declare_serial/implement_serial macro must be used to serialize List objects;

Call the list serialize () function

This step is the serialized list m_phonelist, that is, the member function serialize () that calls m_phonelist (). Where can I call it? Remember, no matter when you select "save", "Save as", or "open" from the "file" menu, the serialize () function of the document class will be executed, therefore, you must call the serialize () function of m_phonelist in the serialize () function of the document class.
In this way, when you select Save/Save As from the File menu, m_phonelist will be saved to the selected file. Similarly, whenever you select open, the list information saved in the file is loaded into m_phonelist. M_phonelist is serialized as follows:

m_PhoneList.Serialize(ar);

As long as the above statement is called in the serialize () function of the document class, the AR must be passed in as a parameter, which will complete all the work of serializing the m_phonelist list data. You do not have to perform other operations in the IF statement.

Custom serialization

--Example program: arch

If you do not need to select a file for serialization, you still need to serialize data from or to a specific file. This section describes how to create and customize a carchive object. Create a new single-document SDI application named Arch. Select cformview for the View class. There are two edit boxes and two buttons in the view. The edit box is used to input data. The save to file button is used to serialize the input data to a file, the "load from file" button is used to extract data from the file. For simplicity, the file is hard-coded.
The operation code for "Save to file" is as follows:

// Update m_var1 and m_var2 updatedata (true) with the screen input; // create the file C:/arc. arccfile F; F. open ("C: // arc. arc ", cfile: modecreate | cfile: modewrite); // create a carchive object and associate the file with the object carchive AR (& F, carchive: Store ); // serializes m_var1 and m_var2 to the document ar <m_var1 <m_var2; // closes the document ar. close (); // close the file F. close ();

The operation code for "load from file" is as follows:

// Open the file C:/arc. arccfile F; If (F. open ("C: // arc. arc ", cfile: moderead) = false) return; // create a carchive object and associate the file with the object carchive AR (& F, carchive: load ); // extract data from the object and assign the value to the member variable ar> m_var1> m_var2; // close the document ar. close (); // close the file F. close (); // update the updatedata (false) on the screen );

The above is an example of three MFC serialized data. The memo program functions to serialize data to files, and the PHN program serializes the C ++ Object List to files, arch is customized serialization. For detailed implementation details, download the source code.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.