2011-08-24 62 views
1

當我在序列化過程中嘗試調用「TestSerialize」類中的方法時,出現以下問題。Boost.Serialization:在序列化過程中調用類方法時出錯

這裏是我的代碼:

class TestSerialize 
{ 
public: 
    std::string GetVal() { return Val + "abc"; } 
    void SetVal(std::string tVal) { Val = tVal.substr(0, 2); } 

protected: 

    std::string Val; 

    friend class boost::serialization::access; 
    template<class Archive> void save(Archive & ar, const unsigned int version) const 
    { 
     using boost::serialization::make_nvp; 
     std::string tVal = GetVal(); // Error here 
     ar & make_nvp("SC", tVal); 
    } 

    template<class Archive> void load(Archive & ar, const unsigned int version) 
    { 
     using boost::serialization::make_nvp; 
     std::string tVal; 
     ar & make_nvp("SC", tVal); 
     SetVal(tVal); 
    } 
    BOOST_SERIALIZATION_SPLIT_MEMBER(); 
}; 

int main() 
{ 
    TestSerialize tS; 

    std::ofstream ofs("test.xml"); 
    boost::archive::xml_oarchive oa(ofs, boost::archive::no_header); 
    oa << BOOST_SERIALIZATION_NVP(tS); 
    ofs.close(); 

    return 0; 
} 

,我遇到的錯誤是: 'TestSerialize :: GETVAL':無法從 '常量TestSerialize' '這個' 指針轉換爲 'TestSerialize &'

這個錯誤只發生在「保存」而不是「加載」

我想知道爲什麼我會得到這個錯誤。我想知道什麼Boost.Serialization做這樣我們有這兩個不同的行爲。 我使用Boost庫1.47.0

回答

2

save是一個const函數,只能調用其他const函數。 GetVal不是。改變它:

std::string GetVal() const { ... }