未调用析构函数,程序异常退出时出现问题
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;
}
我的问题是,虽然所有的编译都没有问题,但当运行时,主函数会冻结——不过上面的"总和"是计算出来的。想知道这是因为析构函数没有被调用还是无法被调用。如果有人有任何想法,我将不胜感激。
我认为您的代码在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[]
相关文章:
- 警告处理为错误这里有什么问题
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我不断收到 [错误] ID 返回 1 退出状态错误,但看不到问题所在
- 退出简单while循环时出现问题
- 编译问题:在函数"_start"中:未定义对"主"的引用 collect2:错误:ld 返回 1 个退出状态
- 退出分段错误 ¿如何解决此问题?
- 在C++中使用exit()退出程序有问题吗
- "Extern"对象问题:错误:Id 返回 1 个退出状态
- 程序在没有输入的情况下退出,它有基本的,驱动的类属性初始化问题
- 关于退出的三个问题
- 在C++测试家庭作业问题中的字符串输入时无法退出循环(作为数据验证)
- C++ 运行失败:退出值 2 - 我的代码出了什么问题?
- 简单c++程序Id的问题返回1退出状态
- 问题5.1-QMessageBox错误?如果在QDialog隐藏时调用了QMessageBox,则程序退出(0)
- 我已经设法将一些代码从 msdn 移植到 MinGW 以从子应用程序捕获标准输出,但它不会退出,这里有什么问题?
- getchar 有什么问题(因为程序在没有检查的情况下退出循环)
- 未调用析构函数,程序异常退出时出现问题
- 这个项目有什么问题吗?为什么不退出循环