我正在製作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