【问题标题】:Pass data from object in class A to class B将数据从 A 类中的对象传递到 B 类
【发布时间】:2021-11-10 09:06:28
【问题描述】:

刚接触 C++ 中的类和对象并尝试学习一些基础知识

我有 TStudent 类,其中存储了 student 的姓名、姓氏和年龄,我还有在 main 中访问并插入数据的构造函数。 我想要做的是:拥有TRegistru 类,我必须在其中添加我的对象数据,以便我可以将其存储在那里,然后我可以将数据保存在data.bin 中并从数据,然后我想把数据放回类中并打印出来。

问题是:以什么方式以及在第二类中添加我的对象的最佳方式是什么,以便我最终可以按照我在 cmets 中描述的方式使用它们,这样我就不会无需更改 main 中的任何内容

到目前为止,这是我的代码:

#include <iostream>    

using namespace std;

class TStudent
{
public:
    string Name, Surname;
    int Age;

    TStudent(string name, string surname, int age)
    {
        Name = name;
        Surname = surname;
        Age = age;
        cout <<"\n";
    }
};

class TRegistru : public TStudent 
{
public:
    Tregistru()        
};

int main()
{
    TStudent student1("Simion", "Neculae", 21);
    TStudent student2("Elena", "Oprea", 21);
    TRegistru registru(student1);//initialising the object
    registru.add(student2);//adding another one to `registru`
    registru.saving("data.bin")//saving the data in a file
    registru.deletion();//freeing the TRegistru memory
    registru.insertion("data.bin");//inserting the data back it
    registru.introduction();//printing it

    return 0;
}

【问题讨论】:

  • 您想了解序列化。 (这看起来很像“请为我写下所有代码”的问题。期待它被关闭。)
  • 参考。 Boost.JSONBoost.Serialization。该建议的通用版本:每当您需要完成标准库中没有的事情时,请先检查Boost
  • 我认为您的 TRegistru 课程格式不正确

标签: c++ class constructor destructor


【解决方案1】:

因此问题是关于将数据从 A 传递到 B,我不会评论文件处理部分。

这可以通过多种方式完成,但这里是最简单和最通用的一种。通过调用 TRegistru::toString() 可以将添加到 TRegistru 的每个 TStudent 序列化为单个字符串,然后可以轻松地将其写入文件。

Demo

class TStudent
{
public:
    std::string Name, Surname;
    int Age;

    std::string toString() const
    {
        return Name + ";" + Surname + ";" + to_string(Age);
    }
};


class TRegistru
{
public:
    void add(const TStudent& student) 
    {
        students.push_back(student);
    }

    void deletion() 
    {
        students.clear();
    }

    std::string toString() const
    {
        std::string ret{};
        for(const auto& student : students)
        {
            ret += student.toString() + "\n";
        }
        return ret;
    }

    std::vector<TStudent> students;
};

【讨论】:

  • 对不起,但是在 main 中调用 registru 时给我一个错误,我猜它对构造函数很有吸引力,但我不知道为什么它无法继续
  • @Vlad 这里有一个工作演示:godbolt.org/z/1KWT1rnjP
  • 是的,谢谢,这有点帮助,但重点是 main 应该保持不变
  • @Vlad,没有理由修改 main.您只需实现 save() 方法,该方法将调用 toString() 序列化 TRegistru 并将结果字符串写入文件。然后,您可以编写类似的函数 fromString(const std::string& input) 反序列化字符串并根据您从该字符串读取的数据创建 TStudent 实例。在这种情况下,它非常简单,通过分隔符查找标记或拆分字符串,这里有很多代码 sn-ps 展示了如何做到这一点。
猜你喜欢
  • 2021-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多