2011-11-02 455 views
0

我在編程時仍然是初學者,但遇到了錯誤「賦值爲左操作數所需的左值」,我不確定如何解決此問題通過其他各種討論後。當我重載某些操作符時,錯誤出現在我爲矩陣創建的類中。下面是代碼的一部分,錯誤:「需要作爲左操作數賦值的左值」

#ifndef MATRIX_H 
#define MATRIX_H 

#include <iostream> 
#include "MVector.h" 


class Matrix { 
private: 
vector<double> columns; 
vector<vector<double> > A; 
public: 
//constructor 
explicit Matrix(){}; 
explicit Matrix(int n,int m):columns(m),A(n,columns){}; 
explicit Matrix(int n,int m,double x):columns(m,x),A(n,columns){}; 
//destructor 
~Matrix(){}; 
//equate matrices 
Matrix &operator=(const Matrix &rhs) {A=rhs.A;return *this;}; 
//set all values to a double 
Matrix &operator=(double x) 
{ 
    int rows=this->rows(); 
    int cols=this->cols(); 
    for (int i=0;i<rows;i++) 
    { 
     for (int j=0;j<cols;j++) 
     { 
      A[i][j]=x; 
     } 
    } 
} 
//access data in matrix (const) 
double operator()(int i,int j) const {return A[i][j];}; 
//access data in matrix 
double operator()(int i,int j) {return A[i][j];}; 
//returns the number of rows 
int rows() const {return A.size();}; 
//returns the number of cols 
int cols() const {return columns.size();}; 
//check if square matrix or not 
bool check_if_square() const 
{ 
    if (rows()==cols()) return true; 
    else return false; 
} 
}; 

,這是重載運算產生錯誤

const Matrix operator+(const Matrix &A,const Matrix &B) 
{ 
//addition of matrices 
//check dimensions 
if (!(A.cols()==B.cols()) || !(A.rows()==B.rows())) 
{ 
    cout << "Error: Dimensions are different \n Ref: Addition of Matrices"; 
    throw; 
} 
else 
{ 
    int dim_rows = A.rows(); 
    int dim_cols = B.cols(); 
    Matrix temp_matrix(dim_rows,dim_cols); 
    for (int i=0;i<dim_rows;i++) 
    { 
     for (int j=0;j<dim_cols;j++) 
     { 
      temp_matrix(i,j)=A(i,j) + B(i,j); 
     } 
    } 
    return temp_matrix; 
} 
} 

我認爲我做錯了什麼,如果有人能幫助解釋的一個什麼,我做錯了,這將非常感激。謝謝您的幫助!

+1

我相信你想在你的錯誤處理程序塊中拋出一些東西。 'throw;'只在catch-block中有效,即有一個待處理的異常,並且可能導致直接調用terminate() – sstn

回答

2

這意味着你不能分配右值表達式的結果,在這種情況下,operator()(int,int)返回的臨時值。你可能想改變你的非const operator()(int,int)在Matrix類是:

double& operator()(int x, int y) { return A[i][j]; } 

此外(和無關的問題),你可能希望簡化矩陣類,並只存儲尺寸和一個一維矢量來存儲所有的元素。然後訪問器會執行一些基本的算術(類似於row*columns()+column)以獲得一維向量中的實際值。

+0

我改變了它,它編譯並運行正常。感謝您提供豐富的答案! – blaahhrrgg

相關問題