2015-11-02 106 views
0

我正在嘗試使用模板爲我的鏈接列表類編寫重載賦值運算符,但我不斷收到錯誤。使用重載運算符模板時出現錯誤=

任何幫助我做錯了會很好。

我收到的錯誤是「行外定義不符合LL中的任何聲明」。

聲明我是:

const LL<T>& operator=(const LL<T> &rhsObj); 

和實現是:

template<typename T> 
LL<T>& LL<T>::operator=(const LL<T>& rhsObj) const 
{ 
    if (this!= &rhsObj) 
    { 
     //no self assignment so OK to continue 
     //deallocate left hand side memory 
     this->clear(); 

     count = 0; 
     head = NULL; 

     cout <<"calling function copyList()" << endl; 

     count = 0; 
     head = NULL; 

     string diCode = ""; 
     int onNode = 0; 

     if(rhsObj.head == NULL) 
     { 
      cout <<"other list is empty, nothing to do" << endl; 

     } 
     else 
     { 
      onNode =0; 
      Node<T> *otherCurrent = rhsObj.head; 
      while(otherCurrent != NULL) 
      { 
       int duplicateInfo; 
       duplicateInfo = otherCurrent->info; 

       push_back(duplicateInfo); 

       otherCurrent = otherCurrent ->next; 
       onNode++; 

      } //END while(otherCurrent != NULL) 

     } // END else block of if (otherLL.head == NULL) 

    } // END if (this != &rhsObj) 

    return *this; 
} 
+4

賦值成員函數不應該是const。 –

+0

您是否在.h和.cpp文件中分割您的模板類?如果是這樣,請參閱:http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file – NathanOliver

+1

'LL :: operator ='需要是'LL : :operator =' –

回答

0

在更新的代碼,這個錯誤是因爲你的宣言是:

const LL<T>& operator=(const LL<T> &rhsObj); 

但試圖執行的是:

LL<T>& LL<T>::operator=(const LL<T>& rhsObj) const 

const的位置其實很重要。第一個意思是函數返回一個const的引用;第二個意思是你不能修改函數中的*this

尾隨const是函數簽名的一部分,因此編譯器不會考慮您的實現與最初聲明的函數相對應。所以它看起來像你試圖添加一個未在類定義中聲明的新函數,這是不允許的。

要解決此問題,請使實現與聲明匹配(將const從末尾移動到開頭)。