2013-11-25 42 views
0

我在MFC程序中創建了一個雙向鏈表。 每當我想加載變量,程序崩潰。我不能創建一個新的節點。 有誰知道如何序列化一個雙向鏈表。MFC序列化雙向鏈表

這裏是我的功能:

void CDatenbankDoc::Serialize(CArchive& ar) 
{ 
    if (ar.IsStoring()) 
    { 
     Actual = Start; 
     while (Actual) 
     { 
      ar << Actual->name; 
      ar << Actual->adresse; 
      ar << Actual->email; 
      ar << Actual->fax; 
      ar << Actual->firma; 
      ar << Actual->geburtsdatum; 
      ar << Actual->geschlecht; 
      ar << Actual->land; 
      ar << Actual->ort; 
      ar << Actual->plz; 
      ar << Actual->telefon; 
      ar << Actual->vorname; 
      Actual = Actual->next;  
     } 
    } 
    else 
    { 
     Actual = Start; 
     while (InsertedAll != true) 
     { 
      Actual->next = new Node; 
      Actual->next->previous = Actual; 
      ar >> Actual->next->name; 
      ar >> Actual->next->vorname; 
      ar >> Actual->next->adresse; 
      ar >> Actual->next->email; 
      ar >> Actual->next->fax; 
      ar >> Actual->next->firma; 
      ar >> Actual->next->geburtsdatum; 
      ar >> Actual->next->geschlecht; 
      ar >> Actual->next->land; 
      ar >> Actual->next->ort; 
      ar >> Actual->next->plz; 
      ar >> Actual->next->telefon; 
      Actual = Actual->next; 
      if (!Actual->next) 
      { 
       InsertedAll = true; 
      } 
     } 
    } 
} 
+2

您的基本問題是,當您存儲鏈接列表時,您不會存儲任何指示列表何時結束的內容。我不確定當你閱讀這份名單時你期望發生什麼魔法。如何首先存儲列表的* length *。然後你的閱讀程序可以使用這個值來判斷何時停止閱讀。 – john

+0

你確定'實際=實際 - >下一步;'沒有任何檢查? – Zigma

+0

知道列表何時結束的最好方法是首先遍歷列表並獲取成員的數量。先寫入流中。就像所有其他MFC容器使用歸檔流一樣。 – xMRi

回答

1

請嘗試下面的代碼。我沒有測試過,所以可能會有一些錯誤,但你應該明白。 我假定Start是CDatenbankDoc的成員。

int CDatenbankDoc::GetLinkedListSize() 
{ 
    // This function returns the length of the linked list whose 1st element 
    // is pointed by the Start member. 
    // The implementation is left as an exercice 

}  

void CDatenbankDoc::Serialize(CArchive& ar) 
{ 
    if (ar.IsStoring()) 
    { 
     ar << GetLinkedListSize(Start) ; // save size of linked list 

     Actual = Start; 
     while (Actual) 
     { 
      ar << Actual->name; 
      ar << Actual->adresse; 
      ... 
      Actual = Actual->next;  
     } 
    } 
    else 
    { 
     int size ; 
     ar >> size ; // get size of linked list 

     Node *previous = NULL ; 

     for (int i = 0; i < size; i++) 
     { 
      Node *Actual = new Node;  // assuming Node constructor inits 
             // pointers to Null     
      if (previous) 
       previous->next = actual ; 

      Actual->previous = previous ; 

      if (i == 0) 
       Start = Actual ; 

      // beware, the order of serialisation and deserialisazion must 
      // be the same during reading and writing which is not the case 
      // in the code you posted !!! 

      ar >> Actual->name; 
      ar >> Actual->adresse; 
      ... 

      previous = Actual ; 
     } 
    } 
} 

更好的解決方案是將鏈表封裝到具有Seri​​alize成員函數的類中。

1

if (!Actual->next)訪問尚未初始化的值。