Visual c++ 在c+中使用析构函数+;删除指针
我有以下资料:Visual c++ 在c+中使用析构函数+;删除指针,visual-c++,destructor,Visual C++,Destructor,我有以下资料: //in Matrix.h class Matrix { public: Matrix (int _row1=1, int _col1=1); Matrix(const Matrix &); ~Matrix(); int row1; //int row2; int col1; double **m; //other functions and members... void Print(int i
//in Matrix.h
class Matrix
{
public:
Matrix (int _row1=1, int _col1=1);
Matrix(const Matrix &);
~Matrix();
int row1;
//int row2;
int col1;
double **m;
//other functions and members...
void Print(int id);
}
//In Matrix.cpp
Matrix::Matrix(int _row1, int _col1): row1(_row1),col1(_col1)
{
m=(double **) new double[row1];
for(long p=0;p<row1;p++) m[p]=(double *) new double[col1];
for(long p=0;p<row1;p++) for (long q=0;q<col1;q++) m[p][q]=0.0;
}
//copy constructor
Matrix::Matrix(const Matrix &Mat){
m=(double **) new double[row1];
**m=**Mat.m;// copy the value
}
// Destructor
Matrix::~Matrix(void){
//We need to deallocate our buffer
delete[] *m;
delete [] m;
//Set m to null just in case
m=0;
cout<<" Freeing m "<<endl;
}
void Matrix::Print(int id)
{
cout<<"Element ID: "<<id<<endl;
for(int i=0; i<row1; i++) {
for(int j=0;j<col1;j++) {
cout<<m[i][j];
if(j==col1-1) cout<<"\n";
}
}
system("PAUSE");
}
elem[e].d0 = matel[i].OrgD;// Both Matrix
elem[e].d0.Print(1); // checking to see if at all copied
在以下位置失败:
void Matrix::Print(int id){
//...
cout<<m[i][j];//here
...//
}
Matrix::Operator=...
{
o.m[p] 0xcdcdcdcd double *
CXX0030: Error: expression cannot be evaluated // in the debugger
}
我注意到,如果有析构函数删除'm',那么使用调用对象的'.m'的所有函数都会发生同样的情况。希望得到一些答案。在您正在使用的构造函数中
m=(double **) new double[row1];
for(long p=0;p<row1;p++) m[p]=(double *) new double[col1];
m=(double**)新的double[row1];
对于(长p=0;pif,您使用m[i][j]
这被解释为(m[i])[j]
,即(m+i*sizeof(double))+j*sizeof(double)
。根据您的体系结构,这可能会起作用,但通常您不能假设sizeof(double*)==sizeof(double)
。我认为,m[0][0]应该总是有效的,因为在这种情况下sizeof并不重要。好吧,所以我改变了m=(double**)new(double)[row1];对于(long p=0;pOk),问题似乎是你的复制构造函数做了奇怪的事情。它分配一些内存(不足以容纳整个矩阵,只有一行),然后只复制一个值(第一行)。只有在复制矩阵时才会失败吗?顺便说一下:为矩阵分配后续内存是个好主意(new double[row*col]
)…我在哪里添加分配后续内存的代码。不,它总是失败。(即,如果我注释掉复制构造函数)
Matrix::Operator=...
{
o.m[p] 0xcdcdcdcd double *
CXX0030: Error: expression cannot be evaluated // in the debugger
}
m=(double **) new double[row1];
for(long p=0;p<row1;p++) m[p]=(double *) new double[col1];