2010-10-02 103 views
2
void add(sparseMatrix<T> &b, sparseMatrix<T> &c); // c is output 

sparseMatrix<T> operator+(sparseMatrix<T> &b); 

我創建其由矩陣術語的單鏈表(矩陣項包含行,列,和值)的ArrayList的稀疏矩陣。我無法重載+運算符。我有正常工作的add方法,但是當我嘗試用它來重載+運算符,我得到了以下錯誤:C++:重載+運算符的稀疏矩陣

sparseMatrix.cpp: In function ‘int main()’: 
sparseMatrix.cpp:268: error: no match for ‘operator=’ in ‘c = sparseMatrix<T>::operator+(sparseMatrix<T>&) [with T = int](((sparseMatrix<int>&)(& b)))’ 
sparseMatrix.cpp:174: note: candidates are: sparseMatrix<T>& sparseMatrix<T>::operator=(sparseMatrix<T>&) [with T = int] 
make: *** [sparseMatrix] Error 1 

這裏是我的重載+運算符實現:

sparseMatrix<T> sparseMatrix<T>::operator+(sparseMatrix<T> &b) 
{ 
     sparseMatrix<T> c; 

add(b, c); 
return c; 

} 

給出錯誤的主線是c = a + b(a,b,c都是稀疏矩陣)。請注意,如果我做a.add(b,c),一切正常。當我做a = b等時,我也重載了=運算符,但似乎是在我發佈的錯誤消息中抱怨它。我真的不確定問題是什麼。有任何想法嗎?

+0

嗯,從快速掃描您的問題,確認+運算符的輸出。它是否會返回它應該的? – 2010-10-02 13:11:47

+0

當我嘗試使用+運算符時,我甚至無法編譯它,所以我無法檢查輸出 – murkilator 2010-10-02 13:14:09

+0

您可能對'boost :: ublas :: sparse_matrix'感興趣:http://www.boost。 org/doc/libs/1_44_0/libs/numeric/ublas/doc/matrix_sparse.htm – 2010-10-02 13:19:55

回答

7

note: candidates are: sparseMatrix& sparseMatrix::operator=(sparseMatrix&)

operator=應採取常量參考。

如果引用不是const,則它不能綁定到臨時對象,因此賦值運算符不能用於由a + b創建的臨時對象。

(同樣是真實的operator+,這裏也的說法應該是const sparseMatrix<T> &此外,該方法應該聲明爲const,因爲它不修改對象時,它被稱爲上。)

+0

+1。趕上':))' – 2010-10-02 13:22:04

+0

我仍然在學習C++和const總是給我一些問題。當我嘗試將const添加到operator =方法中,就像你說的,我得到以下錯誤:sparseMatrix.cpp:183:error:passing'const arrayList >'as'this'argument of'T&arrayList :: get(int)[with T = chain >]'丟棄限定符:行183爲:for(int j = 0; j murkilator 2010-10-02 13:26:43

+0

@ murkilator:看起來你的'get()'方法也應該是const,比如'int get(int i)const {...}'。不改變它們被調用的對象的方法應該被聲明爲const,以便編譯器知道在常量對象上使用它們是可以的。 – sth 2010-10-02 13:33:21

0

某事:有正確診斷問題:

但我會讓你的運營商更標準。

class sparseMatrix 
{ 
    sparseMatrix(sparseMatrix const& copy); 
    sparseMatrix& operator=(sparseMatrix const& copy); 

    sparseMatrix& add(sparseMatrix const& value) // Add value to the current matrix 
    { 
     // Do Work. 
     return *this; 
    } 

    // Re-use add to implement the += operator. 
    sparseMatrix& operator+=(sparseMatrix const& rhs) 
    { 
     return add(rhs); 
    } 

    // Two things here: 
    // 
    // Implement the operator + in terms of the operator += 
    // 
    // This basically means that you make a copy of one parameter then add the other 
    // value two it. Because + is symmetric it does not matter which you copy and which 
    // you add to the copy. 
    // 
    // So we pass the parameter by value this will provide an implicit copy 
    // generated by the compiler. This will also help the compiler with NRVO 
    // Then we just add (*this) to the copy of the rhs. 
    sparseMatrix operator+(sparseMatrix rhs) 
    { 
     return rhs += *this; 
    } 
}