当我调试以下代码时,我被告知存在访问冲突。我尝试将赋值运算符中的this->arr[i][j]
更改为*(this->arr[i][j])
,但这不起作用,因为我被告知这是非法的间接。
标题
#ifndef MATRIX_H
#define MATRIX_H
class Matrix
{
public:
Matrix(int rSize=3, int cSize=3);
Matrix(const Matrix& m);
~Matrix();
bool setValue(int rSize, int cSize, int value);
bool getValue(int rVal, int cVal, int& value)const;
Matrix& operator= (const Matrix& m);
private:
int rowSize;
int columnSize;
int** arr;
};
来源
#include<iostream>
#include<cmath>
#include"Matrix.h"
using namespace std;
Matrix::Matrix(int rSize,int cSize)
{
columnSize = cSize;
rowSize = rSize;
arr = new int* [rowSize];
for(int i=0; i<rowSize; i++)
arr[i] = new int[columnSize];
for(int j=0; j<rowSize; j++)
{
for(int k=0; k<columnSize; k++)
arr[j][k] = 0;
}
}
Matrix::Matrix(const Matrix& m)
{
columnSize = m.columnSize;
rowSize = m.rowSize;
arr = new int* [rowSize];
for(int i=0; i<rowSize; i++)
{
arr[i] = new int [columnSize];
}
for(int i=0; i<rowSize; i++)
{
for(int j=0; j<columnSize; j++)
arr[i][j] = m.arr[i][j];
}
}
Matrix::~Matrix()
{
for(int i = 0; i < rowSize; ++i)
delete [] arr[i];
delete [] arr;
}
bool Matrix::setValue(int rVal, int cVal, int value)
{
if((rVal<0)||(cVal<0)||(rVal>rowSize-1)||(cVal>columnSize-1))
return false;
arr[rVal][cVal] = value;
return true;
}
bool Matrix::getValue(int rVal, int cVal, int& value)const
{
if((rVal<0)||(cVal<0)||(rVal>rowSize-1)||(cVal>columnSize-1))
return false;
value = arr[rVal][cVal];
return true;
}
Matrix& Matrix::operator= (const Matrix& m)
{
if(&m == this)
return(*this);
if(((this->rowSize)!= m.rowSize) || ((this->columnSize) != m.columnSize))
{
for(int i=0; i<rowSize; i++)
delete []arr[i];
delete[]arr;
rowSize = m.rowSize;
columnSize = m.columnSize;
arr = new int* [m.rowSize];
for(int r=0; r<rowSize; r++);
}
for(int j=0; j<rowSize; j++)
{
for(int k=0; k<columnSize; k++)
this->arr[j][k] = m.arr[j][k];
}
return(*this);
}
驱动程序
#include<iostream>
#include"Matrix.h"
using namespace std;
void main()
{
Matrix m(4, 5);
Matrix m2(m);
m2.setValue(1,2,12);
int x;
m2.getValue(1,2,x);
Matrix m3;
m3 = m2;
}
答案 0 :(得分:0)
矩阵和安培; Matrix :: operator =(const Matrix&amp; m)
for(int r=0; r<rowSize; r++);
你忘了分配:
arr[r] = new int [columnSize];