【原創】C++中對象的序列化,原創對象序列化
1、對象序列化
對象的序列化是指將對象的狀態信息轉換為可以存儲或者傳輸的形式的過程。對象的反序列化是與序列化相反的過程。
在序列化期間,對象將其當前的狀態寫入到臨時或者永久性的存儲區,可以通過從存儲區讀取或者反序列化對象的狀態,重新創建該對象。
通過序列化,可以將對象從一個應用域發送到另一個應用域中,或者通過網絡連接將對象數據發送到另一台主機。
博文中將對象序列化到文件中。
2、C++下對象序列化的實現
1)將一個類的一個對象序列化到文件
這是最簡單的情況,一個類中只定義一個數據成員。

![]()
1 //Srlz1.cpp: 將一個類的一個對象序列化到文件
2 #include <iostream>
3 #include <fcntl.h>
4 #include <vector>
5 #include <stdio.h>
6 using namespace std;
7
8 //定義類CA
9 //數據成員:int x;
10 //成員函數:Serialize:進行序列化函數
11 // Deserialize反序列化函數
12 // Show:數據成員輸出函數
13 class CA
14 {
15 private:
16 int x; //定義一個類的數據成員。
17
18 public:
19 CA() //默認構造函數
20 {
21 x = 0;
22 }
23 CA(int y):x(y) //定義構造函數,用初始化列表初始化數據成員
24 {
25 }
26 virtual ~CA() //析構函數
27 {
28 }
29 public:
30 //序列化函數:Serialize
31 //成功,返回0,失敗,返回0;
32 int Serialize(const char* pFilePath) const
33 {
34 int isSrlzed = -1;
35 FILE* fp; //define a file pointer
36 //以讀寫方式打開文件,並判斷是否打開;
37 if ((fp = fopen(pFilePath, "w+")) == NULL)
38 {
39 printf("file opened failure\n");
40 return -1; //若打開失敗,則返回-1;
41 }
42 //調用fwrite函數,將對象寫入文件;
43 isSrlzed = fwrite(&x, sizeof(int), 1, fp);
44
45 //判斷寫入是否成功;
46 if ((-1 == isSrlzed) || (0 == isSrlzed))
47 {
48 printf("Serialize failure\n");
49 return -1; //若寫入失敗,則返回-1;
50 }
51 if(fclose(fp) != 0) //關閉文件
52 {
53 printf("Serialize file closed failure.\n");
54 return -1;
55 }
56 printf("Serialize succeed.\n");
57 return 0; //序列化成功,返回0;
58 }
59
60 //反序列化函數:
61 //成功,返回0,失敗,返回-1;
62 int Deserialize(const char* pFilePath)
63 {
64 int isDsrlzed = -1;
65 FILE* fp;
66 //以讀寫方式打開文件,並判斷是否打開;
67 if ((fp = fopen(pFilePath, "r+")) == NULL)
68 {
69 printf("file opened failure.\n");
70 return -1;
71 }
72 //調用fread函數,讀取文件中的對象 ;
73 isDsrlzed = fread(&x, sizeof(int), 1, fp);
74 //判斷是否成功讀入
75 if ((-1 == isDsrlzed)||(0 == isDsrlzed))
76 {
77 printf("Deserialize failure.\n");
78 return -1; //若讀取失敗,則返回-1;
79 }
80 if(fclose(fp) != 0)
81 {
82 printf("Deserialize file closed failure.\n");
83 return -1;
84 }
85 printf("Deserialize succeed.\n");
86 return 0; //反序列化成功,則返回0;
87 }
88
89
90 //成員對象輸出顯示函數
91 void Show()
92 {
93 cout<< "in Show():"<< x << endl;
94 }
95 };
View Code
以上代碼定義了class CA,包括:
數據成員:x;
序列化函數:Serialize();
反序列化函數:Derialize();
數據成員輸出函數:Show();
main函數:
1 int main(int argc, char const *argv[])
2 {
3 CA as(100); //定義一個類對象,並初始化;
4
5 //調用序列化函數,將對象as序列化到文件data.txt中;
6 as.Serialize("data.txt");
7
8 CA ad; //定義一個類對象,用來記錄反序列化對象
9 //調用反序列化函數,將文件data.txt中的對象反序列化到ad對象;
10 ad.Deserialize("data.txt");
11
12 ad.Show(); //調用輸出顯示函數;
13
14 return 0;
15
16 }