2013-10-01 51 views
0

我想寫一個鏈接列表的操作符重載,它將採取+的右側,並將該鏈接列表連接到左側的列表。C++運算符+過載單鏈表

類聲明:

List<T>& operator+(const List<T>& right); 

方法:

template <typename T> 
List<T>& List<T>::operator+(const List<T>& right){ 
    List result(*this); 
    while(right->next != NULL){ 
     result->push_back(right->data); 
    } 
    return list; 
} 

司機:

mylist + mylist2; //both list objects already created. 

錯誤消息:

Error: The operation "List<std::string>* + List<std::string>*" is illegal. 

我不確定爲什麼我會收到編譯時錯誤。我的邏輯是將列表中的每個元素放在右側,並將其推到左側列表的後面。思考?

+2

如果你想連接到一個現有的列表,重載'+ ='會更有意義。 '+'運算符應該返回一個新的列表。但是你有兩個大錯誤:你返回一個局部變量的引用,而你似乎試圖添加兩個指針。 – juanchopanza

+1

根據錯誤信息判斷,「mylist1」和「mylist2」不是「List」,它們是指針。你不能添加指針。 – molbdnilo

回答

1

您報告的確切錯誤可能是您沒有顯示的代碼,但重要的是要指出operator+不應該返回參考。你需要一個成員operator

List<T> operator+(const List<T>& right); 

或一個非成員版本,

template <typename T> 
List<T> operator+(const List<T>& lhs, const List<T>& rhs); 

您可以在一個成員+=運營商,在這裏你的lhs元素追加到*this並返回*this方面實現要麼引用。在您的示例的邏輯是有缺陷的,我把它留給你解決這個問題,但這是一般形式:

List<T>& operator+=(const List<T>& rhs) 
{ 
    // append elements from rhs into *this 
    .... 
    return *this; 
} 

operator+實現,那麼就變得非常簡單:

template <typename T> 
List<T> operator+(const List<T>& lhs, const List<T>& rhs) 
{ 
    List<T> tmp = lhs; 
    tmp += rhs; 
    return tmp; 
} 
+0

所以我理解我需要重載operator +和operator + =才能正確連接兩個列表? – user1822789

+0

得到它的工作,感謝您的建議。 – user1822789

+0

@ user1822789你不需要*使用'operator + ='來實現'operator +',但通常這樣做是有道理的。 – juanchopanza