c ++:稀疏矩阵的重载+运算符

mur*_*tor 2 c++ overloading operator-keyword

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

sparseMatrix<T> operator+(sparseMatrix<T> &b);
Run Code Online (Sandbox Code Playgroud)

我正在创建一个稀疏矩阵,它由一个矩阵项单链表的arrayList组成(矩阵项包含行,列和值).我在重载+运算符时遇到问题.我有一个工作正常的添加方法,但是当我尝试使用它来重载+运算符时,我得到以下错误:

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
Run Code Online (Sandbox Code Playgroud)

这是我对重载+运算符的实现:

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

 add(b, c);
 return c;

}
Run Code Online (Sandbox Code Playgroud)

主要给出错误的行是c = a + b(a,b,c都是稀疏矩阵).请注意,如果我执行a.add(b,c),一切正常.我也重载了=运算符,当我执行a = b等工作时,它似乎在我发布的错误消息中抱怨它.我真的不确定问题是什么.有任何想法吗?

sth*_*sth 7

注意:候选者是:sparseMatrix&sparseMatrix :: operator =(sparseMatrix&)

operator=应该采取const参考.

如果引用不是const,则不能绑定到临时,因此赋值运算符不能用于临时创建的a + b.

(同样如此operator+,这里的参数也应该是const sparseMatrix<T> &.另外这个方法应该声明为const,因为它不会修改它被调用的对象.)