我正在制作2D动态矩阵类。问题出现在我的拷贝构造函数和=运算符中。请告诉我我做错了什么。下面是代码:。(在COUT的是检查矩阵超载
private:
int rows;
int coloumns;
float **ptr;
Matrix(const Matrix & M)
{ cout << "copy const called"<<endl;
cout << "1 "<< endl;
if(rows < 0 || column < 0) // To check if its a garbage value or not
{
rows = 0, col = 0;
ptr = NULL;
cout << "2 "<< endl;
}
else if(ptr!=NULL)
{
cout << "3 "<< endl;
for(int i = 0 ; i < col; i++)
{
delete [] ptr[i];
}
cout << "4 "<< endl;
delete [] ptr;
ptr = NULL;
cout << "5 "<< endl;
}
cout << "6 "<< endl;
*this = M;
cout << "7 "<< endl;
}
Matrix operator= (const Matrix &M)
{
if(this == &M)
{
return *this;
}
if(row!=0 && columns != 0)
{
for(int i = 0 ; i < columns; i++)
{
delete [] ptr[i];
}
delete [] ptr;
ptr = NULL;
}
rows = M.rows; col = M.columns;
ptr = new float *[rows];
for(int i = 0; i < rows; i++)
{
ptr[i] = new float [col];
}
for(int i = 0; i< rows ; i++)
{
for(int j=0 ; j< columns ;j++)
{
ptr[i][j] = M.ptr[i][j];
}
}
return *this;
}
int main()
{
Matrix M1(2,3);
Matrix M2(M1);
M2(0, 0) = 1;
}
它停在“*此= M”的拷贝构造函数。此外,我想确认的是,当我在=运算符返回的东西,它把整个的“*此= M”的地方,或只是取代中号
注:? 不准使用矢量
“出现问题”是不是很描述。出现什么问题? –
cout <<“7”将不会打印。 – chillax
它在复制构造函数中的“* this = M”处停止。 另外,我想确认当我在=运算符中返回某些东西时,是否代替整个“* this = M”,或者只是替换M? – chillax