在简单的矩阵类植入中,我得到“访问冲突读取位置0xDDDDDDDD”

时间:2019-01-21 00:16:56

标签: c++ operator-overloading

我正在尝试在cpp中实现一个简单的矩阵类,但出现此错误

  

访问冲突读取位置0xDDDDDDDD

仅在Visual Studio中出现问题,在“ Clion”中这确实是可行的,但我更喜欢VS。

我的头文件看起来像这样

.h

#pragma once
#include <iostream>

using namespace std;

class matrix
{
    int row, col;
    int **mat;

public:
    matrix(){}

    matrix(int _row, int _col);

    matrix(const matrix &m);

    ~matrix();

    void mat_pop(int i, int j, int in) {

        this->mat[i][j] = in;
    }

    matrix& operator=(const matrix &) ;

    matrix operator+(const matrix &m) const;

};

.cpp

#include "pch.h"
#include "matrix.h"




matrix::matrix(int _row, int _col):row(_row), col(_col)
{

    mat = new int*[row];
    for (int i = 0; i < row; i++) {

    mat[i] = new int[col]();
    }



 }
matrix::matrix(const matrix & m)
{
    row = m.row;
    col = m.col;
    mat = m.mat;

}

matrix::~matrix()
{
    delete []mat;


}

matrix& matrix::operator=(const matrix &m) 
{

    this->~matrix();
    col = m.col;
    row = m.row;
    construct_matrix(row, col);

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

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

            mat[i][j] = m.mat[i][j];

        }

    }


    return *this;

}

matrix matrix::operator+(const matrix &m) const
{

    matrix mat1(row,col);


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

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

            mat1.mat[i][j]  += mat[i][j] + m.mat[i][j];

        }

    }

    return mat1;
}

和#main

#include "pch.h"
#include <iostream>

using namespace std;

#include "matrix.h"

int main()
{
    matrix a(2, 2), b(2, 2);

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

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

            a.mat_pop(i, j, i);
            b.mat_pop(i, j, j);

        }

    }


    //matrix c = a + b;

    matrix c(2, 2);
    c = a + b ;


    return 0;
}

如果我只是写的话,问题在我使用+运算符时弹出

matrix c = a;

一切正常。

0 个答案:

没有答案