天天看点

【类和对象】多态——定义矩阵类Matrix

题目:

【类和对象】多态——定义矩阵类Matrix
#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;
}