第一次接觸c 中的類和物件,想學習一些基礎知識
。我有一個TStudent類,其中存盤了student的名字、姓氏和年齡,我也有一個建構式,可以在main中訪問并插入資料。
我想做的是:有了TRegistru類,我必須在其中添加我的物件資料,以一種可以存盤它的方式,然后我可以在data.bin中保存資料并釋放資料的記憶體,然后我想把資料放回到類中并列印出來。
問題是:用什么方式&在第二個類中添加我的物件的最佳方式是什么,以便我最終可以按照我在評論中描述的方式來處理它們,這樣我就不必在main中做任何改變了。
這是目前我的代碼:
#include <iostream>
使用 命名空間 std.com.cn>。
class TStudent
{
public:
string Name, Surname;
int 年齡。
TStudent(string name, string surname, int age)
{
名字 = 名字。
Surname = surname;
年齡 = 年齡。
cout <<"
"。
}
};
class TRegistru : public TStudent
{
public:
Tregistru()
};
int main()
{
TStudent student1("Simion", "Neculae", 21)。
TStudent student2("Elena", "Oprea", 21)。
TRegistru registru(student1);//初始化物件。
registru.add(student2);//向`registru`添加另一個人。
registru.saving("data.bin")//將資料保存在一個檔案中。
registru.deletion();//釋放TRegistru存盤器。
registru.insertion("data.bin");//inserting the data back it。
registru.introduction();//printing it。
return 0;
}
uj5u.com熱心網友回復:
因此問題是關于從A到B的資料傳遞,我將不對檔案處理部分進行評論。
這可以通過多種方式實作,但這里有一個最簡單和最通用的方式。通過呼叫 TRegistru::toString(),你將每個添加到 TRegistru 的 TStudent 序列化為一個字串,然后可以輕松地寫入檔案。
class TStudent
{
public:
std::string Name, Surname;
int 年齡。
std::string toString() const
{
return Name ";" Surname ";" to_string(Age)。
}
};
class Tegistru
{
public:
void add(const TStudent& student)
{
students.push_back(student)。
}
void deletion()
{
students.clear()。
}
std::string toString() const
{
std::string ret{}。
for(const auto& students : students)
{
ret = student.toString() "
"。
}
return ret;
}
std::vector<TStudent> students。
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/328124.html
標籤:
