Reputation: 21
void add(sparseMatrix<T> &b, sparseMatrix<T> &c); // c is output
sparseMatrix<T> operator+(sparseMatrix<T> &b);
I'm creating a sparse matrix which is made up of an arrayList of singly linked lists of matrix terms (matrix terms contain the row, column, and value). I'm having trouble overloading the + operator. I have an add method which works fine, but when I try to use it to overload the + operator I get the following errors:
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
Here is my implementation for the overloaded + operator:
sparseMatrix<T> sparseMatrix<T>::operator+(sparseMatrix<T> &b)
{
sparseMatrix<T> c;
add(b, c);
return c;
}
The line in main that gives the error is c = a + b (a, b, c are all sparse matrices). Note that if I do a.add(b,c) everything works fine. I have also overloaded the = operator which works when I do a = b etc. but it seems to be complaining about it in the error message I posted. I'm really not sure what the problem is. Any ideas?
Upvotes: 2
Views: 1209
Reputation: 264381
sth: has correctly diagnosed the problem:
But I would make your operators more standard.
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;
}
}
Upvotes: 0
Reputation: 229583
note: candidates are: sparseMatrix& sparseMatrix::operator=(sparseMatrix&)
Your operator=
should take a const reference.
If the reference isn't const, it can't be bound to a temporary, so the assignment operator can't be used for the temporary created by a + b
.
(The same is true for operator+
, here also the argument should be const sparseMatrix<T> &
. Additionally this method should be declared as const, since it doesn't modify the object it is called on.)
Upvotes: 7