c++ - 如何在 C++ 中对两个复杂矩阵求和?
问题描述
我有一个复数类,其数据成员是 im(虚部)和 re(实部)。现在我想对来自类 Matrix(A 和 B)的 2 个矩阵求和,并将总和放入另一个矩阵(C)中。这是我尝试过的。有什么建议吗?
我得到的错误是
no match for 'operator[]' (operand types are 'Matrix' and 'int')
inline Matrix& operator+(Matrix& A, Matrix& B)
{
Matrix *C = new Matrix;
C->rows = A.rows;
C->columns = A.columns;
for(int i = 0; i < A.rows; i++)
for(int j = 0; j < A.columns; j++)
C[i][j] = A[i][j] + B[i][j];
}
return **C;
}
解决方案
在类中添加一个运算符“+”,例如:
Matrix Matrix::operator+(const Matrix &other){
Matrix result = Matrix<T>(rows, other.columns);
if (this->rows == other.columns && this->columns == other.rows) {
for (int i = 0; i < this->rows; i++) {
for (int j = 0; j < this->columns; j++) {
result.n[i][j] = other.n[i][j] + this->n[i][j];
}
}
}
return result;
}
和运算符'='复制结果
Matrix& Matrix::operator=(const Matrix &other ){
if(this->columns<=other.columns && this->rows<=other.rows){
for(int i=0;i<this->rows;i++){
for(int j=0;j<this->columns;j++){
this->n[i][j]=other.n[i][j];
}
}
return (*this);
}else{
printf("ERROR");
}
}
推荐阅读
- python - 如何修改下面的 Python 代码以将字符附加到 Pandas 中字符串的开头?
- mysql - Pentaho Data Integration 8.1 存储库 mysql 错误 (conn:50787)
- spring-boot - Jboss 6.4 的 Spring Boot 2.0.0 War 部署问题
- jquery - Django 导入-导出 KeyError: u'id'
- javascript - d3.js:对嵌套数组进行排序
- vba - Excel VBA 进度条显示基于活动工作表的宏进度
- java - 尝试在 Spring Boot/Spring Security Web 应用程序中打开 .css 文件时,为什么会出现“405 - Method Not Allowed”错误?
- javascript - Emblem.js 中子组件的数据向下绑定
- git - Heroku Build api问题
- reactjs - 使用 Context API 示例解释 React 高阶组件