我不明白怎么了

时间:2019-11-25 10:53:04

标签: c++ matrix memory dynamic-memory-allocation garbage

这是我自己的Matrix类:

class Matrix {
private:
    int row;    // rows
    int col;    // columns
    double** matrix;    // pointer to this matrix

public:
    Matrix();
    Matrix(int row, int col);//creating matrix based on two params
    Matrix(double** matx, int row, int col); //Here is a problem
    Matrix(Matrix& N);//copy constructor
    ~Matrix();
    //first, second and fourth constructors works good 

    int getRow();
    int getCol();
    void changeSize(int row, int col);
    void randValues();
    void writeValues();
};

这里是构造函数的主体,该构造函数需要以一个存在的矩阵为参数,并根据提供的矩阵创建一个新的(不是副本构造函数)

Matrix::Matrix(double** matx, int row, int col){
    //allocated memory for new matrix
    matrix = new double*[row];
    for (int i = 0; i < row; i++){
        matrix[i] = new double[col];
    }
    //    //copy values to new matrix
    for(int i=0; i<row; i++)
    {
        for(int k = 0; k < col; k++)
        {
            matrix[i][k] = matx[i][k];
        }
    }
};
int main(){

    double** test = new double *[5];
        for(int i = 0; i < 5; i++){
            test[i] = new double;
        }

        for(int i = 0; i < 5; i++){
            for(int k = 0; k < 5; k++){
                test[i][k] = 0.11;
                cout << test[i][k] << "  ";//just for make me sure if is ok
            }
            cout << "\n";
        }

        Matrix *matx = new Matrix(test,5,5);
        matx->writeValues();

    return 0;
}

当我运行程序时,它们在控制台上写了很多零值和少量垃圾,最后的结果是:进程返回-1073741819(0xC0000005)执行时间:2.162 s

0 个答案:

没有答案