【发布时间】:2020-07-15 21:02:46
【问题描述】:
我正在尝试用 C++ 编写一个矩阵程序,但我得到错误无效操作数到二进制表达式。我知道这与我的带有“*”的重载运算符有关。 在我的代码 main.cpp 中:
Matrix mat7=mat1*3;
cout<<"Mult m1 * 3;"<<endl;
print_matrix(mat7);
在这一部分中,我将矩阵 1 乘以 3。
我需要帮助的是我的 matrix.cpp
Matrix Matrix::operator * (const Matrix& mat2){
if(this->num_cols==mat2.num_rows){
Matrix result(num_rows, mat2.num_cols);
for(int i=0; i<num_rows; i++){
for(int j=0; j<mat2.num_cols; j++){
result.matrix[i][j]=0;
for(int k=0; k<this->num_cols; k++){
result.matrix[i][j]+=matrix[i][k]*mat2.matrix[k][j];
}
}
}
return result;
}
else{
Matrix result(num_rows, num_cols);
for(int i=0; i<num_rows; i++){
for(int j=0; j<num_cols; j++){
result.matrix[i][j]=0;
}
}
return result;
}
}
这让我的乘法运算符重载到乘以另一个矩阵。
我的问题是如何使用整数做同样的事情?
【问题讨论】:
-
将参数设为
int? -
看看下面的帖子,看看它看起来像一个体面的 Matrix 实现:codereview.stackexchange.com/q/149669.