c ++序列化包含字符串和指向另一个对象的指针的对象

时间:2017-03-28 17:24:16

标签: c++ serialization

这个问题是我大学实验室工作的一部分!

我有两个班级,salt 'service*' state.apply schedulestudent。这两个类的基本接口如下所示:

student.h

course

course.h

    class student
    {
    private:
        int id;
        string name;
        int course_count;

    public:
        student();
        student * student_delete(int);
        void student_add(int);
        static student * student_add_slot(int);
        int get_id();
        int get_course_count();
        string get_name();
        void set_course_count(int);
        void student_display();
        course * course_records;
        void operator= (const student &);
    };

我被要求将学生对象(仅限成员变量)写入二进制模式的文件中。现在我明白我必须序列化对象,但我不知道该怎么办。我知道C ++提供了基本类型的基本序列化(如果我错了,请纠正我)但我不知道如何在学生课程记录变量 >对象(动态分配的数组)到文件。

请询问您是否需要额外的东西。谢谢!

2 个答案:

答案 0 :(得分:2)

您有ISO CPP标准的最佳答案。

我无法解释清楚。

请仔细阅读问题编号(4,9,10,11)以获取具体问题的答案。

https://isocpp.org/wiki/faq/serialization

答案 1 :(得分:0)

因为您只是尝试序列化成员变量,所以问题相当简单。这是一个小例子,展示了如何将这样一个简单的变量序列序列化为连续的字节数组(字符)。我没有测试代码,但概念应该足够清晰。

// serialize a string of unknown lenght and two integers
// into a continuous buffer of chars
void serialize_object(student &stu, char *buffer)
{
    // get a pointer to the first element in the
    // buffer array
    char *char_pointer = buffer;
    // iterate through the entire string and
    // copy the contents to the buffer
    for(char& c : stu.name)
    {
        *char_pointer = c;
        ++char_pointer;
    }
    // now that all chars have been serialized we
    // cast the char pointer to an int pointer that
    // points to the next free byte in memory after
    // the string
    int *int_pointer = (int *)char_pointer;
    *int_pointer = stu.id;
    // the compiler will automatically handle the appropriate
    // byte padding to use for the new variable (int)
    ++int_pointer;
    // increment the pointer by one size of an integer
    // so its pointing at the end of the string + integer buffer
    *int_pointer = stu.course_count;
}

现在缓冲区变量指向连续内存数组的开头 包含字符串和两个整数变量打包成字节。