【问题标题】:invalid operands to binary expression error二进制表达式错误的无效操作数
【发布时间】: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;
   }
}

这让我的乘法运算符重载到乘以另一个矩阵。

我的问题是如何使用整数做同样的事情?

【问题讨论】:

标签: c++ matrix


【解决方案1】:

我认为定义一个方法 Matrix Matrix::operator* (int factor) 应该可以满足您的需求。

【讨论】:

  • 这是正确的,但是不建议对整数值使用 const 引用,因为在寄存器中按值传递更快,并且不会引起任何别名问题编译器
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多