2017-02-25 8 views
0

二重リンクリストクラスで5のルールを実装する方法を理解するのが難しいです。私はそれらのコンセプトを得て、それをコード化する方法だけで失われてしまいます。私はデストラクタとコピーオペレータを試みましたが、残りのスタンドではまだ進んでいます。ヘルプ/ガイダンスは感謝しています、ありがとうございます。リンクリストクラスで代入演算子を実装する方法

デストラクタ/コピー:

~DList() { 

    Node* current = front_; 

    while (current != back_) 
    { 
      front_ = front_->next_; 
      delete current; 
      current = front_; 

    } 

} 

    // copy ctor 
    DList(const DList& rhs) { 

      const Node* current = rhs.front_; 
      Node* temp = nullptr; 

      if (current != back_) 
      { 
        front_ = new Node(current->data_); 
        temp = front_; 
        current = current->next_; 
      } 
      while(current != back_) 
      { 
        Node* nn = new Node(current->data_); 
        temp->next_ = nn; 
        temp = temp->next_; 
        current = current->next_; 
      } 

    } 

DList& operator=(const DList& rhs){ //copy assignment // <<---not sure where to begin 

リストCTOR:

DList() { 


     //Node* front_; 
      front_ = new Node(); // creating front sentinel 
                //Node* back_; 
      back_ = new Node(); // creating back sentinel 
                //make them point to eachother 
      front_->next_ = back_; 
      back_->prev_ = front_; 
      listSz = 0; 

    } 

メイン:あなたが作業コピーコンストラクタを持っている場合(つまり、ないが割り当てを使用し

DList<int> list; 
    DList<int> list2; 
    DList<int>::const_iterator it; 

    cout << list.size() << endl; 
    list.push_front(1); 
    list.push_front(2); 
    list.push_back(3); 
    list.push_front(4); 
    list.print(); 

    std::cout << endl; 

    list2.push_front(11); 
    list2.push_front(12); 
    list2.push_back(13); 
    list2.push_front(14); 
    list2.print(); 

    list2 = list; 
    list2.print(); 

答えて

1

演算子)とデストラクタを使用すると、代入演算子は単純にth次のとおりです。

#include <algorithm> 
//... 
DList& operator=(const DList& rhs) 
{ 
    DList temp(rhs); 
    std::swap(temp.front_, front_); 
    std::swap(temp.back_, back_); 
    std::swap(temp.listSz, listSz); 
    return *this; 
} 

これは基本的にcopy/swap idiomを使用しています。一時オブジェクトは、渡されたDListから作成され、一時オブジェクトの内部は現在のオブジェクトの内部にスワップアウトされます。その後、一時的なものは古い内部構造で消滅します。

+0

深いコピー方法を探しています – bb13

+0

@ bb13 - それは深いコピーです。私は答えでそれを説明しました。 – PaulMcKenzie

+0

ディープコピーがありますか? – bb13

関連する問題