[英]Matrix Class and operator= overloading
我面臨着一個我自己無法解決的小問題。 我正在編寫一個對矩陣執行非常簡單的操作的程序。 問題是,當我嘗試執行以下操作時:
Matrix first(5);
Matrix e;
first.identityMatrix();
e = first;
cout << first;
cout << e;
簡短說明:我想將正方形矩陣分配給沒有尺寸的矩陣。
二分球什么也沒顯示。 但是,當我將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
。
在分配運算符中,還必須復制尺寸a
和b
。
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部分。 這樣,您的代碼更少,潛在的錯誤更少。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.