c++中的类矩阵

Class matrix in c++

本文关键字:c++      更新时间:2024-04-28

当我输入2个矩阵时,程序停止。它不打印总和,甚至"2个矩阵的总和"也不打印。我不知道这是否都是分配错误,因为当我使用静态数组或向量时,结果是正确的。我不知道怎么修。希望大家帮忙!非常感谢!

#include <iostream>
using namespace std;
class Matrix
{
private:
int** value;
int row;
int col;
public:
Matrix();
Matrix(int, int);
Matrix(const Matrix&);
Matrix operator + (const Matrix&);
friend istream& operator >> (istream&, Matrix&);
friend ostream& operator << (ostream&, Matrix&);
~Matrix(void);
};
int main(void)
{
Matrix a, b, c;
cout << "Input 1st matrix: ";
cin >> a;
cout << a;
cout << "Input 2nd matrix: ";
cin >> b;
cout << b;
c = a + b;
cout << "Sum of 2 matrices: " << c << endl;
return 0;
}
Matrix::Matrix()
{
this->row = 0;
this->col = 0;
value = new int *[row];
for(int i = 0; i < row; i++)
{
value[i] = new int[col];
}
for(int i = 0; i < row; i++)
{
for(int j = 0; j < col; j++)
{
value[i][j] = 0;
}
}
}
Matrix::Matrix(int b, int c)
{
this->row = b;
this->col = c;
value = new int *[row];
for (int i = 0; i < this->row; i++)
{
value[i] = new int[col];
}
}
Matrix::Matrix(const Matrix &a)
{
this->row = a.row;
this->col = a.col;
value = new int *[row];
for (int i = 0; i < row; i++)
{
value[i] = new  int[col];
}
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
value[i][j] = a.value[i][j];
}
}
}
istream& operator >> (istream& ip, Matrix& a)
{
cout << endl;
cout << "Input rows: ";
ip >> a.row;
cout << "Input cols: ";
ip >> a.col;
a.value = new int* [a.row];
for (int i = 0; i < a.row; i++)
{
a.value[i] = new int[a.col];
}
for (int i = 0; i < a.row; i++)
{
for (int j = 0; j < a.col; j++)
{
cout << "[" << i << "]" << "[" << j << "]" << " : ";
ip >> a.value[i][j];
}
}
return ip;
}
ostream& operator << (ostream& op, Matrix& a)
{
for (int i = 0; i < a.row; i++)
{
for (int j = 0; j < a.col; j++)
{
op << a.value[i][j] << " ";
}
op << endl;
}
return op;
}
Matrix Matrix::operator + (const Matrix &a)
{
Matrix tg;
for (int i = 0; i < a.row; i++)
{
for (int j = 0; j < a.col; j++)
{
tg.value[i][j] = this->value[i][j] + a.value[i][j];
}
}
return tg;
}
Matrix::~Matrix(void)
{
for (int i = 0; i < this->row; i++)
{
delete[] value[i];
}
delete[] value;
}

在这段代码中,您认为tg有多少行和列?

Matrix Matrix::operator + (const Matrix &a)
{
Matrix tg;
for (int i = 0; i < a.row; i++)
{
for (int j = 0; j < a.col; j++)
{
tg.value[i][j] = this->value[i][j] + a.value[i][j];
}
}
return tg;
}

应该是

Matrix Matrix::operator + (const Matrix &a)
{
Matrix tg(a.row, a.col); // make tg same size as a
for (int i = 0; i < a.row; i++)
{
for (int j = 0; j < a.col; j++)
{
tg.value[i][j] = this->value[i][j] + a.value[i][j];
}
}
return tg;
}
相关文章:
  • 没有找到相关文章