在下面的函数中。
template<class T>
Matrix<T> Add(const Matrix<T> &matrix1, const Matrix<T> &matrix2, bool to_add) {
Matrix<T> result = matrix1;
int matrix_height = result.height();
int matrix_width = result.width();
for (int i = 0; i < matrix_height; i++) {
for (int j = 0; j < matrix_width; j++) {
if (to_add) {
result(i, j) += matrix2(i, j);
} else {
result(i, j) -= matrix2(i, j);
}
}
}
return result;
}
下面一行是编译。result(i, j) += matrix2(i, j);
而这行没有: result(i, j) -= matrix2(i, j);
我得到的错误是:
没有可行的重载 '-=' result(i, j) -= matrix2(i, j);
我已经为const和non const实现了操作符<<。
const T &Matrix<T>::operator()(int row, int column) const;
T &Matrix<T>::operator()(int row, int column);
那么是什么导致了这个问题?T=int
我可以打电话 -=
但编译器却说不一样。
试试这个,写这个代码。
template<class T>
T Add(const T &matrix1, T &matrix2, bool to_add) {
T result = matrix1;
int matrix_height = result.height();
int matrix_width = result.width();
for (int i = 0; i < matrix_height; i++) {
for (int j = 0; j < matrix_width; j++) {
if (to_add) {
matrix2 = i+j;//ADD THIS
result = result+matrix2;//CHANGE THIS
} else {
matrix2=i-j;//ADD THIS
result = result-matrix2;//CHANGE THIS
}
}
}
return result;
}