2015-02-11 49 views
0

美好的一天「無效的類型非常量引用的初始化...」clone()函數中的錯誤

我忙於在C++中實現線性數據結構。我正在用我的clone()函數。一行代碼似乎是爲了我,但也許錯誤是在複製構造函數。 我得到的錯誤: linkedList.C:22:32:錯誤:類型'LinkedList &'類型的非常量引用無效初始化'LinkedList *' 返回新的LinkedList(* this);

template<class T> 
LinkedList<T>& LinkedList<T>::clone() 
{ 
    return new LinkedList<T>(*this); 
} 

template<class T> 
LinkedList<T>::LinkedList(const LinkedList<T>& other) 
{ 

    Node<T>* newNode; 
    Node<T>* current; 
    Node<T>* trailCurrent; 

    if(head != NULL) 
     clear(); 
    if(other.head == NULL) 
     head = NULL; 
    else 
    { 
     current = other.head; 
     head = new Node<T>(current->element); 
     head->next = NULL; 

     trailCurrent = head; 
     current = current->next; 

     while(current != NULL) 
     { 
      newNode = new Node<T>(current->element); 
      trailCurrent->next = newNode; 

      trailCurrent = current; 
      current = current->next; 
     } 
    } 
} 
+0

首先,在我看來,你用一個指針初始化一個引用,不是嗎? – undermind 2015-02-11 17:21:01

+1

該函數被取消返回LinkedList &,但您的代碼返回LinkedList *。有一個類型不匹配,所以編譯器會提醒你。 – thang 2015-02-11 17:21:47

回答

2

你可以改變你的克隆功能:

template<class T> 
LinkedList<T>* LinkedList<T>::clone() 
{ 
    return new LinkedList<T>(*this); 
} 

記住調用clone函數後釋放內存。

+0

謝謝。事情只是,我們可能不會更改頭文件(所以我們可能不會更改函數原型) – Mat 2015-02-11 17:25:34

+0

@Mat事情是......那件事是不相關的。這是正確的解決方法(禁止智能指針和RAII建模,這是真正的*正確*方法)。向您提供標題的教師留下了一個選項,用於正確清理動態分配('delete&refvar;'),如果使用不正確,該選項會留下大量內存泄漏,這很容易犯錯。也許那個標題的作者應該坐在教室的另一邊。 – WhozCraig 2015-02-11 17:32:11

+1

誰寫了這個標題是一個白癡。 http://stackoverflow.com/questions/752658/is-the-practice-of-returning-a-c-reference-variable-evil – thang 2015-02-11 17:33:55

相關問題