我在编程时仍然是初学者,但遇到了错误“赋值为左操作数所需的左值”,我不确定如何解决此问题通过其他各种讨论后。当我重载某些操作符时,错误出现在我为矩阵创建的类中。下面是代码的一部分,错误:“需要作为左操作数赋值的左值”
#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;
}
}
我认为我做错了什么,如果有人能帮助解释的一个什么,我做错了,这将非常感激。谢谢您的帮助!
我相信你想在你的错误处理程序块中抛出一些东西。 'throw;'只在catch-block中有效,即有一个待处理的异常,并且可能导致直接调用terminate() – sstn