【发布时间】:2018-03-24 07:47:21
【问题描述】:
我已经定义了一个模板类,并且重载了一个操作符,这样:
template<class T = bool>
class SparseMatrix
{
public:
SparseMatrix(int msize);
//Multiplication by vectors or matrices
SparseMatrix<double> operator *(SparseMatrix<T> &s);
//Matrix exponentiation
SparseMatrix<double> pow(int n);
};
我认为,运算符的特定形式并不重要。随着运算符重载,现在我可以执行以下操作:
int main(void)
{
int i;
SparseMatrix<bool> s = SparseMatrix<bool>(4);
SparseMatrix<bool> t = SparseMatrix<bool>(4);
//Here goes some code to fill the matrices...
SparseMatrix<double> u = t*s; //And then use the operator
return 0;
}
这很好用。没有错误,它返回正确的结果等。但是现在,我想填充类的pow方法,这样:
template<class T>
SparseMatrix<double> SparseMatrix<T>::pow(int n)
{
if (n == 2)
{
return (this * this); //ERROR
}
else
{
int i=0;
SparseMatrix<double> s = this * this;
while (i < n-2)
{
s = s * this;
i++;
}
return s;
}
}
但是,当我转到main 并写类似SparseMatrix<double> u = t.pow(2); 的内容时,我收到一条错误消息,指出invalid operands of types 'SparseMatrix<bool>*' and 'SparseMatrix<bool>*' to binary 'operator*'。正如我之前所说,bool 矩阵的乘法定义很好,那么,为什么编译器会抱怨呢?我对this 的使用不当吗?我该如何解决这个错误?
感谢您的帮助。
【问题讨论】:
-
您似乎忘记了
this是指向对象的指针。如果您真的阅读了错误消息(其中提到了SparseMatrix<bool>*类型),应该非常明显。 -
顺便说一句,所有
const都不见了。 -
如果你实现
operator*=()和operator*(),你会发现它更容易和更有效。
标签: c++ class templates compiler-errors