【问题标题】:c++ Serializing an object containing string and pointer to another objectc ++序列化包含字符串和指向另一个对象的指针的对象
【发布时间】:2017-03-28 17:24:16
【问题描述】:

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

我有两个班级,studentcourse。两个类的基本接口如下所示:

student.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 &);
    };

course.h

class course
{
private:
    string id;
    short credit_hours;
    string description;

public:
    course();
    course * remove_course(course*, int);
    static course * add_course_slots(course*, int);
    int add_course(course*,int);
    string get_id();
    string get_description();
    void course_display(int);
    short get_credit_hours();
};

我被要求以二进制模式将 student 对象(仅成员变量)写入文件。现在我明白我必须序列化对象,但我不知道应该如何进行。我知道 C++ 为基本类型提供了基本序列化(如果我错了,请纠正我)但我不知道如何在 student 中序列化一个字符串和一个 course records 变量 > 对象(这是一个动态分配的数组)到一个文件。

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

【问题讨论】:

  • 您想仅序列化成员变量还是整个类?
  • @AlexHG 只有类的成员变量(我假设你的意思也是函数序列化)。我将对其进行编辑以使其清楚。
  • 您还应该查看 boost 序列化库。
  • @jwimberley 谢谢!我会看看。由于这是一项实验室工作,我必须遵守要使用的要求和方法。

标签: c++ serialization


【解决方案1】:

您可以从 ISO CPP 标准中获得最佳答案。

我没有比这更好的解释了。

请浏览问题编号 (4,9,10,11) 以获得您特定问题的答案。

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

【讨论】:

  • 这是一个很好的资源。谢谢!
【解决方案2】:

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

// 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;
}

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

【讨论】:

  • 谢谢!但是,仅凭知识,如果他必须将一个对象作为一个整体进行序列化,将如何进行。
  • 你的意思是一个只包含变量的对象?
  • 是的!然后可以直接将其复制到对象中。
  • 我看到有一个公共变量 course_records 也需要序列化。 (course_records 是动态分配的数组)。
猜你喜欢
  • 2015-08-07
  • 2013-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-25
  • 2014-01-07
  • 2013-03-14
  • 1970-01-01
相关资源
最近更新 更多