错误:“左值作为赋值的左操作数”

时间:2011-11-02 10:23:45

标签: c++

我仍然是编程的初学者,但我遇到了错误“左值作为左操作数所需的左值”,我不确定如何在查看各种其他讨论后解决此问题。当我重载某些运算符时,错误出现在我为Matrices制作的类中。这是代码的一部分,

#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 个答案:

答案 0 :(得分:2)

这意味着您无法分配 rvalue-expression 的结果,在这种情况下是operator()(int,int)返回的临时值。您可能希望将Matrix类中的非常量operator()(int,int)更改为:

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

此外(与问题无关)您可能希望简化矩阵类并仅存储尺寸和单个一维向量来存储所有元素。然后访问器将执行一些基本算术(类似row*columns()+column)以获得一维向量中的实际值。