簡體   English   中英

未調用析構函數,程序退出異常

[英]Destructor not called and issue with program exiting abnormally

我有以下代碼用於定義Matrix類。 頭文件中的定義如下:

#ifndef MATRIX_H
#define MATRIX_H
/* General matrix class */

class Matrix
{
    public:
        Matrix(int m, int n, double ini);
        virtual ~Matrix();
        Matrix(const Matrix& other); //copy ctor
        Matrix& operator=(const Matrix& other); //assignment operator;
        double operator()(int i, int j) const; //access element in the matrix
        double& operator() (int i, int j); //set element in the matrix
        friend Matrix operator+(const Matrix& mat1, const Matrix& mat2); //Matrix addition
        friend Matrix operator+(const Matrix& mat1, double a); //scaler multiplication
        int dimension() const {return rows*cols;} //getter method for dimension
    protected:
    private:
        int rows; //number of rows in the matrix
        int cols; //number of cols in the matrix
        double* d; //pointer to the representation of the matrix
};

與問題相關的部分的實現如下所示。

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

Matrix::Matrix(int m, int n, double ini):rows{m},cols{n},d{new double[m*n]}
{
        //ctor
        double* p = d;
        for(int i=0;i<rows*cols;i++)
        {
            *p++ = ini;
        }
}

Matrix::~Matrix()
{
    //dtor
    delete []d;
}


Matrix& Matrix::operator=(const Matrix& rhs)
{
    if (this == &rhs) return *this; // handle self assignment
    if (rows*cols<=rhs.rows*rhs.cols)
    {
        delete []d;
        d = new double[rhs.rows*rhs.cols];
        rows = rhs.rows;
        cols = rhs.cols;
        for(int i=0;i<rows*cols;i++)
        {
            d[i] = rhs.d[i];
        }
    }
    //assignment operator
    return *this;
}

double Matrix::operator()(int i, int j) const
{
    return d[rows*i + j];
}

double& Matrix::operator()(int i, int j)
{
    return d[rows*i+j];
}

現在,我有一個簡單的測試應用程序,它創建一個矩陣,為矩陣中的元素分配值,以及讀取元素的值(給定行號和列號)。

    #include <iostream>
    #include "Matrix.h"
    using namespace std;

    int main()
    {
        int i,j;
        Matrix A(3,2,0.0);
        cout<<A.dimension()<<endl;
    // assign values to matrix elements
        for (i=0;i<3;i++)
            {
                for (j=0;j<2;j++) A(i,j) = 0.1*i*j;
            }

            // access matrix elements
        double sum = 0.0;
        for (i=0;i<3;i++) {
            for (j=0;j<2;j++) sum += A(i,j); }
        cout << "The sum of the matrix elements is ";
        cout << sum << endl;
        return 0;
    }

我的問題是,盡管所有內容都可以毫無問題地編譯,但是運行時,主要功能卻凍結了-盡管上面的“ sum”是計算得出的。 想知道這是由於未調用析構函數還是無法調用析構函數。 非常感謝任何人有任何想法。

我認為您的代碼在operator()中是錯誤的

double Matrix::operator()(int i, int j) const
{
    return d[cols*i + j];
}

double& Matrix::operator()(int i, int j)
{
    return d[cols*i+j];
}

並且您使數組d []溢出

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM