首页 > 解决方案 > 如何在 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;
}

标签: c++oopmatrixsumadd

解决方案


在类中添加一个运算符“+”,例如:

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");
        }
}

推荐阅读