gpt4 book ai didi

c++ - 矩阵重载

转载 作者:行者123 更新时间:2023-11-30 03:43:32 25 4
gpt4 key购买 nike

我正在制作一个 2D 动态 Matrix 类。我的复制构造函数和 =operator 出现问题。请告诉我我做错了什么。这是代码:(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;
}

它在复制构造函数中的“*this = M”处停止。此外,我想确认一下,当我在 = 运算符中返回某些内容时,它会取代整个“*this = M”,还是只是取代 M?

注意:不允许使用 vector 。

最佳答案

您正在进行无限递归。在你复制构造函数中你有

*this = M;

这会调用您声明的类的 operator=

Matrix operator= (const Matrix &M)

可以看到是按值返回的。当您按值(value)返回时,会制作一份拷贝。要制作该拷贝,我们需要调用复制构造。这又会再次调用赋值运算符,后者会调用复制构造函数,并且循环继续进行。

您的复制构造函数可以更正并简化为

Matrix(const Matrix & m) : rows(m.rows), columns(m.columns)
{
ptr = new float*[rows];
for (int i = 0; i < rows; i++)
ptr[i] = new float[columns];

for (int i = 0; i < rows; i++)
for (int j = 0; j < columns; j++)
ptr[i][j] = m.ptr[i][j]
}

请注意我不必检查新类的状态,因为我们知道它是什么,因为我们正在初始化它。一切都未初始化,我们所要做的就是初始化一切,然后将值从一个矩阵复制到新矩阵。

关于您的赋值运算符,您应该让它返回对对象的引用而不是按值返回。这避免了不必要的复制,并允许您将运算符与其他运算符链接起来。

关于c++ - 矩阵重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36014610/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com