代码实现:
#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[r*c];
}
~Matrix()
{
delete[] p;
}
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++) 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;
}
}
};
int main()
{
int r, c;
cin >> r >> c;
Matrix A(r,c);
A.input();
Matrix B(r,c);
B.input();
Matrix D(A);
D.show();
Matrix E(B);
E.show();
Matrix C = A + B;
C.show();
return 0;
}
运行结果:
疑惑:
拷贝构造函数:Matrix(const Matrix &b)
Matrix &b必须为const类型,否则会报错