c++:重载 +稀疏矩阵的运算符
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 等操作时起作用,但它似乎在我发布的错误消息中抱怨它。我真的不确定问题是什么。有什么想法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的
operator=
应该采用const引用。如果引用不是 const,则无法将其绑定到临时对象,因此赋值运算符不能用于
a + b
创建的临时对象。(
operator+
也是如此,这里的参数也应该是const稀疏矩阵&
。此外,这个方法应该声明为 const,因为它不修改它所调用的对象。)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 beconst sparseMatrix<T> &
. Additionally this method should be declared as const, since it doesn't modify the object it is called on.)sth:已经正确诊断了问题:
但是我会让你的操作员更加标准。
sth: has correctly diagnosed the problem:
But I would make your operators more standard.