我做了一個經典的鏈表來模擬一個可以得到任何你想要的類型的數組。當然,你可以刪除和添加器官,所有方法都可以正常工作。保存並從鏈表中加載數據到一個二進制文件C++
現在我必須編寫寫入和讀取二進制文件的方法,我真的不知道該怎麼辦 我試過各種方法寫入文件,到目前爲止我還沒有能力取得任何進展,我甚至不知道什麼是錯的代碼,
這就是我的鏈表代碼
template <class T>
class LinkedList
{
private:
struct node
{
T data;
node * next;
};
node* head;
public:
LinkedList();
~LinkedList();
void add(T value);
int find(T value);
bool remove(T value);
void clear();
bool ifEmpty() const;
int size() const;
void display() const;
T getData(int index) const;
T &operator[](int index);
void save(ofstream& out);
};
一部分,這就是保存方法dosent工作
template <class T>
void LinkedList<T>::save(ofstream& out)
{
node* temp = head;
T temp2 = temp->data;
for (int i = 0; i < size(); i++)
{
out.write((const char*)(temp2), sizeof(temp2));
temp = temp->next;
temp2 = temp->data;
}
}
012的代碼
如果你們中的一些專業人員可以給我一個方向,如何做到這一點...
查找「序列化」。如果'T'包含指針,則返回的指針將不會有用。 – nwp
是的,我明白你的意思,但我可以拋出一個異常,不要使用指針或東西的權利? – user8093201
判斷'T'是否包含指針並不容易。如果它是一個「私人」成員呢?通常你會爲各種'T'編寫'std :: string to_string(const T&t)'和'T from_string(const std :: string&s)'函數。對於像'int'這樣的一些類型,你可以自己實現,對於用戶需要的用戶自定義類型。另外看看像[麥片](https://uscilab.github.io/cereal/)這樣的圖書館。 – nwp