2011-08-24 83 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 { ... }