gpt4 book ai didi

c++ - 矩阵类和 operator= 重载

转载 作者:太空宇宙 更新时间:2023-11-04 16:24:20 25 4
gpt4 key购买 nike

我遇到了一个我自己无法解决的小问题。我正在编写一个程序,它在矩阵上实现非常简单的操作。问题是当我尝试做这样的事情时:

Matrix first(5);
Matrix e;

first.identityMatrix();
e = first;
cout << first;
cout << e;

简短说明:我想将方阵分配给没有维度的矩阵。

第二个 cout 没有显示任何内容。但是当我将 Matrix e() 更改为 Matrix e(5) 时,一切正常。我知道错误存在于这段代码中:

Matrix& Matrix::operator=(const Matrix& tmp)
{
if (this->a==0 && this->b == 0)
{
this->matrix = new double*[tmp.a];

for (int i=0;i<tmp.a;i++)
this->matrix[i] = new double[tmp.b];
} else {
try {
if (this->a!=tmp.a || this->b!=tmp.b)
throw wrongSize();
} catch (wrongSize& e) {
e.message();
throw;
}
}

for (int i=0;i<tmp.a;i++)
{
for (int j=0;j<tmp.b;j++)
{
this->matrix[i][j] = tmp.matrix[i][j];
}
}

return *this;
}

经过一些尝试,我猜测内存分配有问题,但我不确定。对我来说,由于我返回了对当前对象的引用,所以它应该可以正常工作。我认为构造函数也可能有用:

Matrix::Matrix()
{
a = 0;
b = 0;
matrix = NULL;
}

Matrix::Matrix(int a)
{
try {
if (a==0)
throw wrongRowOrColNumber();
} catch (wrongRowOrColNumber& e) {
e.message();
throw;
}
this->a = a;
this->b = a;
this->matrix = new double*[a];

for (int i=0;i<a;i++)
matrix[i] = new double[a];
for (int i=0;i<a;i++)
for (int j=0;j<a;j++)
matrix[i][j] = 0;
}

Matrix::Matrix(int a, int b)
{
try {
if (a==0 || b==0)
throw wrongRowOrColNumber();
} catch (wrongRowOrColNumber& e) {
e.message();
throw;
}

if (a==b)
{
try {
if (a==0)
throw wrongRowOrColNumber();
} catch (wrongRowOrColNumber& e) {
e.message();
throw;
}
this->a = a;
this->b = a;
this->matrix = new double*[a];

for (int i=0;i<a;i++)
matrix[i] = new double[a];
for (int i=0;i<a;i++)
for (int j=0;j<a;j++)
matrix[i][j] = 0;
} else {
this->a = a;
this->b = b;
this->matrix = new double*[a];

for (int i=0;i<a;i++)
matrix[i] = new double[b];
for (int i=0;i<a;i++)
for (int j=0;j<b;j++)
matrix[i][j] = 0;
}
}

运算符<<:

friend ostream& operator<<(ostream& buffer, const Matrix& tmp)
{
for (int i=0;i<tmp.a;i++)
{
for (int j=0;j<tmp.b;j++)
{
buffer << tmp.matrix[i][j] << " ";
}
buffer << endl;
}
return buffer;
};

IdentityMatrix:

Matrix& Matrix::identityMatrix()
{
try {
if (this->a!=this->b)
{
throw wrongSize();
}
} catch (wrongSize& e) {
e.message();
throw wrongSize();
}
int row = this->a;

for (int i=0;i<row;i++)
{
for (int j=0;j<row;j++)
{
if (i==j)
this->matrix[i][j] = 1;
else
this->matrix[i][j] = 0;
}
}

return *this;
}

最佳答案

你多次抛出异常并在之后立即捕获它,只是为了显示一条消息并重新抛出。如果您只是显示消息然后抛出异常,则可以保存 try/catch

在您的赋值运算符中,您还必须复制维度 ab

Matrix& Matrix::operator=(const Matrix& tmp)
{
if (this->a==0 && this->b == 0)
{
this->a = tmp.a;
this->b = tmp.b;

this->matrix = new double*[tmp.a];
...
}
...
}

在您的构造函数 Matrix::Matrix(int a, int b) 中,您有一个 if (a == b) ... else。您可以删除 if 部分,只保留 else 部分。这样,您的代码就会更少,出现错误的可能性也会降低。

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

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