C++ 访问冲突读取位置-创建矩阵类

C++ 访问冲突读取位置-创建矩阵类,c++,oop,matrix,C++,Oop,Matrix,这应该是我在OOP课程中的硬件。所以我要求创建矩阵类。代码工作正常-所有方法和新操作数都工作正常,但当我的D`tor为空时,当我在那里编写代码以释放内存时,会出现此错误。谢谢你的帮助 int main() { MyMatrix m1(3, 3); MyMatrix m2(3, 3); MyMatrix res(3, 3); m1.Set(); m2.Set(); cout << m1; cout << m2; res = m1 + m2; cout <<

这应该是我在OOP课程中的硬件。所以我要求创建矩阵类。代码工作正常-所有方法和新操作数都工作正常,但当我的D`tor为空时,当我在那里编写代码以释放内存时,会出现此错误。谢谢你的帮助

int main()
{
MyMatrix m1(3, 3);
MyMatrix m2(3, 3);
MyMatrix res(3, 3);

m1.Set();
m2.Set();

cout << m1;
cout << m2;

res = m1 + m2;

cout << res;

}
intmain()
{
MyMatrix m1(3,3);
MyMatrix m2(3,3);
MyMatrix res(3,3);
m1.Set();
m2.Set();

cout Code工作正常——不,不会。析构函数正在暴露代码中的错误。将其放回原处并修复错误。第二,矩阵
的复制构造函数在哪里?第三,赋值运算符引入内存泄漏,在执行矩阵复制的正确方法上存在偏差。因此我要求创建矩阵类--您可以简单地使用
std::vector matrix;
,而不存在您现在遇到的任何问题。值得一读:注意它是如何使用1D数组并执行数学来进行2D到1D索引的。如您所见,这比处理数组要快得多,也要简单得多。还可以进行一次读取。它将有效地回答下一个问题可能是什么。如果没有正确地编写代码,很难回答这样的问题。当前代码需要的不仅仅是几个小的调整。
MyMatrix::MyMatrix(int row, int col) // C`tor with specific data
{
n = row;
m = col;

matrix = new int* [n]; // Memory  allocation for rows

for (int i = 0; i < n; i++)
{
    matrix[i] = new int[m]; // Memory Allocation for columns
}


for (int i = 0; i < n; i++)
{

    for (int j = 0; j < m; j++)
    {

        matrix[i][j] = 0;

    }
}
}

MyMatrix::~MyMatrix() // Default d`tor 
{

for (int i = 0; i < n; i++)
{
    delete[] matrix[i];
}
delete[] matrix;
}

void MyMatrix::Set()
{
cout << "Enter new row" << endl;
for (int i = 0; i < n; i++)
{

    for (int j = 0; j < m; j++)
    {

        cin >> matrix[i][j];

    }

    if (i != (n - 1))
    {
        cout << "Enter new row" << endl;
    }

  }
}


ostream& operator<<(ostream& out, const MyMatrix& matrix)
{

for (int i = 0; i < matrix.n; i++)
{

    //run in loop on every column.
    for (int j = 0; j < matrix.m; j++)
        //print value with a space.
        out << matrix.matrix[i][j] << "t";
    //at the end of every row jump line.
    out << endl;
}

out << endl;
return out;
}


MyMatrix& MyMatrix::operator= (const MyMatrix& mat1)
{
n = mat1.n;
m = mat1.m;

for (int i = 0; i < n; i++)
{

    for (int j = 0; j < m; j++)
    {

        matrix[i][j] = mat1.matrix[i][j];

    }

}

return *this;

}

const MyMatrix MyMatrix::operator+(const MyMatrix& mat1) const
{
MyMatrix temp(n, m);

for (int i = 0; i < n; i++)
{

    for (int j = 0; j < m; j++)
    {

        temp.matrix[i][j] = matrix[i][j] + mat1.matrix[i][j];

    }

}

return temp;

}
class MyMatrix
{

private:

int **matrix;
int n, m;

public:

MyMatrix(int a, int b);
~MyMatrix();

void Set();

const MyMatrix  operator+ (const MyMatrix& mat1) const;
MyMatrix& operator= (const MyMatrix& mat1);

friend ostream& operator<<(ostream& out, const MyMatrix& matrix);
};