2011-11-02 115 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

相关问题