将数据从 class A 中的对象传递到 class B

Pass data from object in class A to class B

classes 和 c++ 中的对象的新手,正在尝试学习一些基础知识

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

问题是:在第二个 class 中添加我的对象的方式和最佳方式是什么,以便我最终可以按照我在评论中描述的方式使用它们,这样我就不必在 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;
}

因此问题是关于将数据从 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;
};