微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java.io.Serializable的C/C++等价是什么?

java.io.Serializable的C/C++等价是什么?

有关序列化库的引用:

> Serialize Data Structures in C

还有:

> http://troydhanson.github.io/tpl/index.html
> http://www.boost.org/doc/libs/1_41_0/libs/serialization/doc/index.html
> https://developers.google.com/protocol-buffers/docs/cpptutorial#optimization-tips

但是这样的等价性是否存在呢?

所以如果我在Java中有一个抽象类,C/C++中的可序列化类如何?

import java.io.Serializable;

public interface SuperMan extends Serializable{

    /**
     * Count the number of abilities.
     * @return
     */
    public int countAbility();

    /**
     * Get the ability with index k.
     * @param k
     * @return
     */
    public long getAbility(int k);

    /**
     * Get the array of ability from his hand.
     * @param k
     * @return
     */
    public int[] getAbilityFromHand(int k);

    /**
     * Get the finger of the hand.
     * @param k
     * @return
     */
    public int[][] getAbilityFromFinger(int k);

    //check whether the finger with index k is removed.
    public boolean hasFingerRemoved(int k);

    /**
     * Remove the finger with index k.
     * @param k
     */
    public void removeFinger(int k);

}

任何可序列化的C/C++对象可以像Java一样继承吗?

解决方法

没有标准的库类以与Java相同的方式实现序列化.有一些库可以促进序列化,但是对于基本需求,通常可以通过重载这样的插入和提取操作来使您的类可序列化:
class MyType
{
    int value;
    double factor;
    std::string type;

public:
    MyType()
    : value(0),factor(0.0),type("none") {}
    MyType(int value,double factor,const std::string& type)
    : value(value),factor(factor),type(type) {}

    // Serialized output
    friend std::ostream& operator<<(std::ostream& os,const MyType& m)
    {
        return os << m.value << ' ' << m.factor << ' ' << m.type;
    }

    // Serialized input
    friend std::istream& operator>>(std::istream& is,MyType& m)
    {
        return is >> m.value >> m.factor >> m.type;
    }
};

int main()
{
    std::vector<MyType> v {{1,2.7,"one"},{4,5.1,"two"},{3,0.6,"three"}};

    std::cout << "Serialize to standard output." << '\n';

    for(auto const& m: v)
        std::cout << m << '\n';

    std::cout << "\nSerialize to a string." << '\n';

    std::stringstream ss;
    for(auto const& m: v)
        ss << m << '\n';

    std::cout << ss.str() << '\n';

    std::cout << "Deserialize from a string." << '\n';

    std::vector<MyType> v2;

    MyType m;
    while(ss >> m)
        v2.push_back(m);

    for(auto const& m: v2)
        std::cout << m << '\n';

}

输出

Serialize to standard output.
1 2.7 one
4 5.1 two
3 0.6 three

Serialize to a string.
1 2.7 one
4 5.1 two
3 0.6 three

Deserialize from a string.
1 2.7 one
4 5.1 two
3 0.6 three

序列化格式完全取决于程序员,您有责任确保要序列化的类的每个成员本身都是可序列化的(已定义插入/提取操作).您还必须处理字段如何分隔(空格或新行或零终止?).

所有的基本类型都有预定义的序列化(插入/提取)运算符,但是您仍然需要注意可以包含(例如)空格或新行的std :: string等(如果使用空格或新行)行作为您的字段分隔符).

原文地址:https://www.jb51.cc/java/124906.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐