2
void add(sparseMatrix<T> &b, sparseMatrix<T> &c); // c is output

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

マトリックス用語の単一リンクリストのarrayListで構成されるスパースマトリックスを作成しています(マトリックス用語には行、列、および値が含まれます)。+ 演算子のオーバーロードに問題があります。正常に動作する add メソッドがありますが、それを使用して + 演算子をオーバーロードしようとすると、次のエラーが発生します。

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;

}

エラーを与える main の行は c = a + b (a、b、c はすべて疎行列) です。a.add(b,c) を実行すると、すべて正常に動作することに注意してください。a = b などを実行するときに機能する = 演算子もオーバーロードしましたが、投稿したエラーメッセージでそれについて不平を言っているようです。何が問題なのか本当にわかりません。何か案は?

4

2 に答える 2

7

注: 候補は: sparseMatrix& sparseMatrix::operator=(sparseMatrix&)

const参照operator=を取る必要があります。

参照が const でない場合、一時にバインドできないため、代入演算子は によって作成された一時に使用できませんa + b

(同じことが にも当てはまります。operator+ここでも引数は である必要がありますconst sparseMatrix<T> &。さらに、このメソッドは呼び出されたオブジェクトを変更しないため、const として宣言する必要があります。)

于 2010-10-02T13:15:38.413 に答える
0

sth:問題を正しく診断しました:

しかし、私はあなたのオペレーターをより標準的にします。

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; 
   }
}
于 2010-10-02T15:14:30.230 に答える