【发布时间】:2017-09-08 16:21:45
【问题描述】:
我只是没有看到我的错误。关于此错误消息有很多问题,或者答案不适用,或者我看不到它们适用。也许应该改进错误消息?
Matrix a = Matrix(3, 4);
// fill a with values
Matrix c = Matrix(4, 4);
// fill c with values
a *= c - c; //this is where the compile error occurs
当我将行更改为 a *= c 时,它可以工作。所以我想 *= 运算符没有什么问题。
这是 Matrix *= 运算符:
Matrix &Matrix::operator *=(Matrix &B)
{
Matrix M(rows(), B.cols());
for (int i = 0; i<rows(); i++)
{
for (int j=0; j<B.cols(); j++)
{
for (int k=0; k<cols(); k++)
{
M(i,j) = M(i,j) + (*this)(i,k) * B(k,j);
}
}
}
return M;
}
这是 - 运算符:
Matrix operator -(Matrix &A, Matrix &B)
{
//TODO: Check if matrices have same dimensions, exception else
Matrix M(A.rows(), A.cols());
for(int i=0; i<A.rows(); i++)
{
for(int j=0; j<A.cols(); j++)
{
M(i,j) = A(i,j)-B(i,j);
}
}
return M;
}
【问题讨论】:
-
不是问题,但
operator *=不应该返回对本地Matrix的引用。如果有什么可以返回*this -
你可能想读一读,看看如何正确地重载你的操作符:stackoverflow.com/questions/4421706/operator-overloading
-
operator*=预计会修改this的值,然后返回对*this的引用。
标签: c++ c++11 matrix operator-overloading