题目:
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLiAzNfRHLGZkRGZkRfJ3bs92YsYTMfVmepNHLxcGVOFzaE5EeVpHW3BjMMBjVtJWd0ckW65UbM5WOHJWa5kHT20ESjBjUIF2X0hXZ0xCMx81dvRWYoNHLrdEZwZ1Rh5WNXp1bwNjW1ZUba9VZwlHdssmch1mclRXY39CXldWYtlWPzNXZj9mcw1ycz9WL49zZuBnL1QDOzMDN1AjM1ETNwEjMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
#include <iostream>
using namespace std;
class Matrix
{
int* p, rows, cols;
public:
Matrix(int r = 0, int c = 0) //构造函数,初始化数组的行数和列数
{
rows = r, cols = c;
p = new int[rows * cols]; //用一维数组存放二维数组
}
Matrix(const Matrix& b) //拷贝构造函数,形参要用常引用,否则报错
{
rows = b.rows;
cols = b.cols;
if (b.p)
{
p = new int[b.rows * b.cols];
for (int i = 0;i < rows * cols;i++) //把参数矩阵b的元素拷贝到当前矩阵中
p[i] = b.p[i];
}
}
void input() //输入数组值
{
for (int i = 0;i < rows * cols;i++)
cin >> p[i];
}
Matrix operator+(Matrix& b) //重载加法运算符
{
Matrix M(rows, cols);
for (int i = 0;i < rows * cols;i++)
M.p[i] = p[i] + b.p[i];
return M;
}
void operator=(Matrix& b) //重载赋值运算符
{
for (int i = 0;i < rows * cols;i++)
b.p[i] = p[i];
}
void show() //按二维方式输出数组
{
cout << endl;
for (int i = 0;i < rows * cols;i++)
{
cout << p[i] << " ";
if ((i + 1) % cols == 0) cout << endl;
}
}
~Matrix() //析构函数,释放数组空间
{
delete[] p;
}
};
int main()
{
int r, c;
cin >> r >> c; //输入矩阵的行数和列数
Matrix A(r, c);
A.input();
Matrix B(r, c);
B.input();
A.show();
B.show();
Matrix C = A + B; //测试矩阵相加
C.show();
return 0;
}