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

时间:2017-01-18 21:01:39

标签: 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 << res;

}

CPP

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;

}

H档

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);
};

0 个答案:

没有答案