2013-10-29 82 views
1
class MyClass 
{ 
    private: 
     AnotherClass obj; 
     float d; 
     int k; 

    public: 
     MyClass(float d = 0.3, int k = 10); 
     virtual ~MyClass(); 
     // other methods goes here 
} 

对象上/存储/加载c是可以具有允许这个类(MyClass的),以保存到其属性值的磁盘(硬盘驱动器)上,其允许加载一个方法void storeOnDisk(string path){...}和另一种方法磁盘void loadFromDisk(string path)的属性值?++从磁盘

如果可能的话,我应该也呼吁loadFromDisk(path) MyClass中的构造函数(创建另一个构造也许)MyClass中的析构函数,并storeOnDisk(path)使所有电流值可以退出该实例化MyClass的程序时被保存?

+0

它被称为序列化。 – LihO

+0

请看看:[序列化](http://www.parashift.com/c++-faq/serialization.html) – Pol0nium

+1

第一个问题:是的。第二个问题,如果你喜欢,当然。但是我认为如果数据恰好可用并且您希望以某种以前的状态加载,您会想要从析构函数调用storeOnDisk以在对象状态被删除之前保存对象状态,并在构造函数中loadFromDisk。 –

回答

2

这取决于你想达到的目标。但是,通常情况下,你不希望在ctor/dtor中有这样的事情,因为有时候会在C++“副本”和“临时对象”中出现。 Ctors/dtors在被创建/移除时被调用,就像常规对象一样,除非您准备好代码以及

通常保持一个单独的类来处理读/写有点容易。想象一下MyClassStorage class这将是MyClassfriend,并且将只包含两种方法:MyClass read(path)write(path MyClass&)

如果你喜欢在单个类中使用它,或者如果你不想手动完成所有的事情,你可以看看一些序列化框架如Boost :: Serialization。关于如何处理它有许多简短的例子,但是 - 但是 - 你必须先阅读一些关于它的内容。

编辑:

http://www.boost.org/doc/libs/1_45_0/libs/serialization/doc/tutorial.html和 “一个非常简单的情况” 一节。它显示如何读取/写入gps_position类。请注意,这个类iteself非常简单,只是它包含一个额外的serialize函数。这个功能既可以作为读写器工作,也可以“自动地”工作。由于通常你想阅读相同的领域,所以你不需要说两遍(而不是说读-A-B-C和写-A-B-C你说:handleThemForMe-A-B-C)。

然后,在main你有使用的例子。 text_oarchivetext_iarchive充当输出和输入文件。某些gps_position对象已创建并命名为g,然后将其保存到名为filename的文件中,然后从文件中将其读回为newg

实际上,ofstream系列有点太早,可能会引起误解。它只是用于创建oarchive,并可以像ifstream/iarchive一样安全地移动。它可能看起来像这样:

// create class instance 
const gps_position g(35, 59, 24.567f); 

/// .... 

// save data to archive 
{ 
    // create and open a character archive for output 
    std::ofstream ofs("filename"); 
    boost::archive::text_oarchive oa(ofs); 
    // write class instance to archive 
    oa << g; 
    // archive and stream closed when destructors are called 
} 

/// .... 

// ... some time later restore the class instance to its orginal state 
gps_position newg; 
{ 
    // create and open an archive for input 
    std::ifstream ifs("filename"); 
    boost::archive::text_iarchive ia(ifs); 
    // read class state from archive 
    ia >> newg; 
    // archive and stream closed when destructors are called 
} 
+0

是否有任何最小的简单工作代码可以直接用于我的示例使用Boost :: Serialization?因为我不想让事情变得复杂。 – shn

+0

@shn:我已经更新了答案,并提供了一个链接,指向Docs的B:Ser教程以及基本示例如何工作的一些解释。 – quetzalcoatl

+0

谢谢。但是,如果我的课程包含一个矢量>的成员呢? – shn