c++ - Boost.序列化: Error on Calling Class Method during serialization process

标签 c++ boost boost-serialization

在序列化过程中尝试调用“TestSerialize”类中的方法时出现以下问题。

这是我的代码:

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”:无法将“this”指针从“const TestSerialize”转换为“TestSerialize &”

这个错误只发生在“保存”时而不是“加载”

我想知道为什么会出现此错误。我想知道 Boost.Serialization 做了什么使我们有这两种不同的行为。 我使用 Boost 库 1.47.0

最佳答案

save 是一个const 函数,只能调用其他const 函数。 GetVal 不是。改变它:

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

关于c++ - Boost.序列化: Error on Calling Class Method during serialization process,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7170994/

相关文章:

c++ - 在 C++ 中返回类型 T

c++ - 我需要释放指向函数的指针吗?

c++ - 如何使调用代码对被调用的代码一无所知

c++ - 是否可以重用 binary_oarchive 实例?

c++ - 设置服务访问规则

c++ - 在同一台机器上运行客户端和服务器

c++ - boost 线程同步

c++ - 类构造函数上 boost::shared_ptr 的默认值

c++ - 管道序列化

c++ - boost vector<char> 的序列化