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