2014-01-19 44 views
0

我想写一个cpp程序来做与运算符重载的矩阵运算。使用赋值运算符导致编译器错误

我的类矩阵具有以下变量:

int m,n // order of the matrix 
int **M; 

起初,我有一个构造函数和析构函数使用new和delete操作符来分配和**中号释放内存。我也有过载+, - 和*运算符的函数。但是当我运行程序时,我得到了垃圾值作为结果。此外,在运行时,我得到一个错误(检测到glibc)。

在这里的类似问题告诉我,我应该添加一个“深拷贝”二维数组的复制构造函数。我也是这样做的。但同样的问题依然存在。

所以我给overload =运算符添加了一个函数。现在,无论何时使用'='运算符,我都会收到编译时错误(对于调用'Matrix :: Matrix(Matrix)'的匹配函数。

这里是我的功能:

拷贝构造函数

Matrix(Matrix& other) { 
    m=other.m; 
    n=other.n; 

    M= new int *[m]; 
    for(int i=0;i<m;i++) 
    M[i] = new int[n]; 

    //deep copying matrix 
    for(int i=0;i<m;i++) 
    for(int j=0;j<n;j++) 
     M[i][j]=other.M[i][j]; 
} 

超载*:

Matrix Matrix::operator*(Matrix A) { 
    Matrix pro(m,A.n); 
    for(int i=0;i<m;i++) 
    for(int j=0;j<A.n;j++) { 
     pro.M[i][j]=0; 
     for(int k=0;k<n;k++) 
     pro.M[i][j]+=(M[i][k]*A.M[k][j]); 
    } 
    return pro; 
} 

超载=::

Matrix Matrix::operator=(Matrix a) { 
    m=a.m; 
    n=a.n; 
/* 
    M=new int* [m]; 
    for(int i=0;i<m;i++) //I also tried allocating memory in this function 
    M[i]=new int[n]; 
*/ 
    for(int i=0;i<m;i++) 
    for(int j=0;j<n;j++) 
     M[i][j]=a.M[i][j]; 
    return *this; 
} 
在main()
Matrix M1(m,n); 
Matrix M2(p,q); 

//inputting both matrices 

Matrix M3(m,n); 
Matrix M4(m,q); 

M3 = M1 + M2; // Compile Time Error here... 
M3.show(); 

M3 = M1 - M2; //...here... 
M3.show(); 

M4 = M1*M2; //...and here. 
M4.show(); 

编译时错误:调用的Matrix矩阵::(矩阵)“

+0

'矩阵(矩阵&)'我强烈怀疑你想要那样。也许用'const'? –

+0

您还应该使用'const&'作为其他函数中的参数,以避免不断复制矩阵。 –

+0

'Matrix Matrix :: operator =(Matrix a)... return * this;'没有错?它需要一个Matrix(Matrix)构造函数 – user3125280

回答

1
Matrix& Matrix::operator=(const Matrix& a) { 
    m=a.m; 
    n=a.n; 
/* 
    M=new int* [m]; 
    for(int i=0;i<m;i++) //I also tried allocating memory in this function 
    M[i]=new int[n]; 
*/ 
    for(int i=0;i<m;i++) 
    for(int j=0;j<n;j++) 
     M[i][j]=a.M[i][j]; 
    return *this; 
} 

赋值运算符的签名错误没有匹配的功能,使return *this试图调用构造函数类型矩阵(矩阵),它不存在。确保返回上面的参考。

从其他答案谈到有效执行拷贝构造函数和赋值操作符的
+0

除非使用复制和交换习语,否则参数应该作为'const&'传递。 – Manu343726

+0

@ Manu343726对不起复制和粘贴作业,修正 – user3125280

0

除了(你的代码是不是很有效,但它应该工作),似乎只是一个小错误:

Matrix(Matrix& other) { ... }似乎超出了命名空间。更改为:

Matrix::Matrix(const Matrix& other) { ... }

+0

可能它在类定义中,但OP不是很响应 – user3125280