程序清单如下:
----------------------Matrix.h----------------------------------
#include <iostream>
#include <fstream>
#include <math.h>
#include <stdexcept>
#include <memory.h>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
#ifndef _MATRIX_H_
#define _MATRIX_H_
///////////////////////////////////////////
// Declaration of Class Matrix //
///////////////////////////////////////////
class Matrix
{
protected:
double* m_data;
unsigned int m_row;
unsigned int m_col;
unsigned long int m_length;
public:
Matrix();
Matrix(unsigned int row, unsigned int col, double* pdata);
Matrix(Matrix &mat);
~Matrix();
inline unsigned int GetRow(void) { return m_row; };
inline unsigned int GetCol(void) { return m_col; };
inline unsigned long int GetLength(void) { return m_length; };
inline double GetData(unsigned long int pos)
{
return m_data[pos-1];
};
bool IsEmpty(void);
bool Reset(Matrix &mtr);
};
#endif
----------------------Matrix.cpp--------------------------------
#include "Matrix.h"
///////////////////////////////////////////
// Constructor & Destructor //
///////////////////////////////////////////
Matrix::Matrix()
{
m_row = 0;
m_col = 0;
m_length = 0;
m_data = NULL;
}
Matrix::Matrix(unsigned int row, unsigned int col, double* pdata)
{
m_row = row;
m_col = col;
m_length = (unsigned long int)(row * col);
m_data = new double[m_length];
try
{
if (m_data == NULL)
{
throw out_of_range("In constructor of Matrix(unsigned, unsigned, Dot*). Out of memory.");
}
if (pdata == NULL)
{
throw runtime_error("In constructor of Matrix(unsigned, unsigned, Dot*). Pointer is NULL.");
}
unsigned long int i;
for (i=0; i<m_length; i++)
{
m_data[i] = pdata[i];
}
}
catch (out_of_range &err)
{
std::cerr << err.what() << endl;
m_row = 0;
m_col = 0;
m_length = 0;
}
catch (runtime_error &err)
{
std::cerr << err.what() << endl;
m_row = 0;
m_col = 0;
m_length = 0;
}
}
Matrix::~Matrix(void)
{
if (m_data != NULL)
{
delete [] m_data;
}
}
///////////////////////////////////////////
// Member Function //
///////////////////////////////////////////
bool Matrix::IsEmpty(void)
{
if (m_length == 0)
{
return true;
}
else
{
return false;
}
}
bool Matrix::Reset(Matrix &mat)
{
if (!IsEmpty())
{
delete [] m_data;
m_data = NULL;
m_row = 0;
m_col = 0;
m_length = 0;
}
if (!mat.IsEmpty())
{
m_data = new double[m_length];
if (m_data == NULL)
{
return false;
}
else
{
m_row = mat.GetRow();
m_col = mat.GetCol();
m_length = mat.GetLength();
unsigned int long i;
for (i=0; i<m_length; i++)
{
m_data[i] = mat.GetData(i+1);
}
}
}
return true;
}
----------------------Main.cpp----------------------------------
#include "Matrix.h"
double testdata[] = { 1, 2,
1, 3 };
unsigned int row = 2, col = 2;
void main(void)
{
Matrix mtr;
mtr.Reset(Matrix(row, col, testdata));
}
发生问题描述:每次从Reset退出后,发生Matrix(row, col, testdata)构造的局部变量的解析时,在解析函数delete掉申请资源时,就会出错。实在不知道是怎么个问题,请高手指教,谢谢。
错误显示为:
Debug Assertion Failed!