利用Boost庫進行序列化

2021-06-11 08:15:55 字數 1448 閱讀 8529

第一部分:vs2010+boost:

安裝到指定目錄下,例如:

(二)在vs2010中使用boost庫

配置lib路徑

第二部分:序列化

我們希望能夠將類物件的成員變數中的值儲存下來,以便下次直接恢復使用。這可以通過序列化來實現,即將這些變數值保持下來,以後需要時直接將保持值恢復到類物件的成員變數中。簡言之,通過序列化可以保持物件的狀態。

通過boost庫,我們可以方便地實現對類物件的序列化。

person::person()

person::~person()

}person::person(int _age, std::string _name):m_age(_age), m_name(_name)

void person::addscore(const float _score)

即在person類中新增如上紅色部分**即可。在serialize()函式中,序列化類成員變數。這裡根據自己的需要,可以選擇序列化某幾個變數,不一定要全部都序列化。

通過例子可以看到,intrusion version需要修改原先的類。

測試程式:

animal oneanimal(25, "dog") ;

oneanimal.addscore(95.2f) ;

std::ofstream ofs("outanimal.bin", std::ios_base::binary) ;

if (ofs.is_open())

animal otheranimal ;

std::ifstream ifs("outanimal.bin", std::ios_base::binary) ;

if (ifs.is_open())

該例與例1的不同在於:不需要對原來的類進行修改。但這種用法需要類成員變數時public型別的。

plant oneplant(25, "tree") ;

oneplant.addscore(95.2f) ;

std::ofstream ofs("outplant.bin", std::ios_base::binary) ;

if (ofs.is_open())

plant otherplant ;

std::ifstream ifs("outplant.bin", std::ios_base::binary) ;

if (ifs.is_open())

boost庫xml序列化

今天利用編版本的時間研究了一下boost的序列化,特別是xml序列化的東東,還是有很多收穫,記下來怕以後忘記了,人老了,很多東東都記不得了.一 研究boost庫xml序列化要做準備的工作 a.下乙個最新的boost庫記住用1.32版本的,這個版本提供了xml序列化的支援 b.windows下用的vc...

boost序列化與反序列化

include include include include include include include include include include 將字串序列化到檔案 void serialize str to file 從檔案中反序列化處字串 void deserialize file...

利用序列化進行檔案讀寫

在很多應用中我們需要對資料進行儲存,或是從介質上讀取資料,這就涉及到檔案的操作。我們可以利用各種檔案訪問方法完成這些工作,但mfc中也提供了一種讀寫檔案的簡單方法 序列化 序列化機制通過更高層次的介面功能向開發者提供了更利於使用和透明於位元組流的檔案操縱方法,舉乙個例來講你可以將乙個字串寫入檔案而不...