1个回答
展开全部
class Matrix {
public:
Matrix(int _m, int _n, int *coef)
{
m = _m; n = _n;
pCoef = new int[m*n];
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
pCoef[i*n+j] = coef[i*n+j];
}
~Matrix()
{
if (pCoef) {
delete[] pCoef;
pCoef = NULL;
}
}
friend Matrix& operator+(const Matrix& a, const Matrix& b)
{
int *c = new int[m*n];
int m = a.m, n = a.n;
for(int i = 0; i < m*n; i++)
c[i*n+j] = a.pCoef[i*n+j] + b.pCoef[i*n+j];
Matrix mc(m, n, c);
delete[] c;
return mc;
}
private:
int m,n;
int *pCoef;
};
public:
Matrix(int _m, int _n, int *coef)
{
m = _m; n = _n;
pCoef = new int[m*n];
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
pCoef[i*n+j] = coef[i*n+j];
}
~Matrix()
{
if (pCoef) {
delete[] pCoef;
pCoef = NULL;
}
}
friend Matrix& operator+(const Matrix& a, const Matrix& b)
{
int *c = new int[m*n];
int m = a.m, n = a.n;
for(int i = 0; i < m*n; i++)
c[i*n+j] = a.pCoef[i*n+j] + b.pCoef[i*n+j];
Matrix mc(m, n, c);
delete[] c;
return mc;
}
private:
int m,n;
int *pCoef;
};
追问
没有主函数吗
追答
主函数根据需要来写。例如:
int main()
{
int m, n, *a, *b;
// 读取矩阵维度
cin >> m >> n;
a = new int[m*n];
b = new int[m*n];
// 读取矩阵A
for(int i = 0; i >a[i*n+j];
// 读取矩阵B
for(int i = 0; i >b[i*n+j];
// 构造矩阵A、B并进行计算
Matrix A(m, n, a);
Matrix B(m, n, b);
Matrix C = A + B;
// 输出矩阵C (需要将pCoef改为public,或将以下输出过程封装成Matrix的一个method)
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++)
cout << C.pCoef[i*n+j] << " ";
cout<<endl;
}
return 0;
}
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询