mic*_*ael 0 c++ operator-overloading
我面临一个我无法独自解决的问题.我正在编写一个程序,它对矩阵实现非常简单的操作.问题是,当我尝试做这样的事情时:
Matrix first(5);
Matrix e;
first.identityMatrix();
e = first;
cout << first;
cout << e;
Run Code Online (Sandbox Code Playgroud)
简短说明:我想将矩形矩阵分配给没有维度的矩阵.
第二个cout没有显示任何内容.但是当我将Matrix e()更改为Matrix e(5)时,一切都很完美.我知道bug存在于这段代码中:
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;
}
Run Code Online (Sandbox Code Playgroud)
经过一些尝试后我猜测内存分配有问题,但我不确定.对我来说,它应该正常工作,因为我返回对当前对象的引用.我认为构造函数也可能有用:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
运营商<<:
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;
};
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
你多次抛出一个异常并立即捕获它,只是为了显示一条消息并重新抛出.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];
...
}
...
}
Run Code Online (Sandbox Code Playgroud)
在你的构造函数中Matrix::Matrix(int a, int b),你有一个if (a == b) ... else.您可以删除if部分,然后保留其他部分.这样,您可以减少代码,减少错误的可能性.