用c++设计一个矩阵类,要求在矩阵类中重载“+”、“-”、“*”、“=”运算符。

#include<iostream>
using namespace std;
int m, m1, n, n1;
class Rectangle
{
public:
	Rectangle();
	void input();
	Rectangle operator+(Rectangle& A);
	Rectangle operator-(Rectangle& B);
	Rectangle operator*(Rectangle& C);
	Rectangle operator=(Rectangle D);
	void display();
private:
	double x[10][10];
};
Rectangle::Rectangle()
{
	for (int i = 0; i < 10; i++)
	{
		for (int j = 0; j < 10; j++)
		{
			x[i][j] = 0;
		}
	}
}
void Rectangle::input()
{
	if (n1 != 0)
	{
		for (int i = 0; i < m1; i++)
		{
			for (int j = 0; j < n1; j++)
			{
				cin >> x[i][j];
			}
		}
	}
	else
		for (int i = 0; i < m; i++)
		{	
			for (int j = 0; j < n; j++)
			{
				cin >> x[i][j];
			}
	    }
}
Rectangle Rectangle::operator+(Rectangle& A)
{
	Rectangle temp;
	for(int i=0;i<m;i++)
		for(int j=0;j<n;j++)
			temp.x[i][j] = x[i][j] + A.x[i][j];
	return temp;
}
Rectangle Rectangle::operator-(Rectangle& B)
{
	Rectangle temp;
	for (int i = 0; i < m; i++)
		for (int j = 0; j < n; j++)
			temp.x[i][j] = x[i][j] - B.x[i][j];
	return temp;
}
Rectangle Rectangle::operator*(Rectangle& C)
{
	Rectangle temp;
	for (int i = 0; i < m; i++)
		for (int j = 0; j < n; j++)
			for(int c=0;c<n1;c++)
				temp.x[i][c] += x[i][j] * C.x[j][c];
	return temp;
}

Rectangle Rectangle::operator=(Rectangle D)
{
	if (n1 != 0)
		n = n1;
	for (int i = 0; i <m; i++)
	{	
		for (int j = 0; j <n; j++)
			x[i][j] =D.x[i][j];
	}
	return*this;
}

void Rectangle::display()
{
	if (n1 != 0)
		n = n1;
	cout << "计算后的矩阵值是:" ;
	for (int i = 0; i <m; i++)
	{
		cout << endl;
		for (int j = 0; j <n; j++)
			cout << x[i][j] << ' ';
	}
	cout << endl;
}
void main()
{
	int y;
	Rectangle c1, c2, c3;
	cout << "两矩阵相加输入1;\n两矩阵相减输入2;\n两矩阵相乘输入3;\n:";
	cin >> y;
	if (y == 1) 
	{
		cout << "请输入矩阵行数和列数:";
		cin >> m >> n;
		cout << "请输入第一个矩阵:" << endl;
		c1.input();
		cout << "请输入第两个矩阵:" << endl;
		c2.input();
		c3 = c1 + c2;
		c3.display();
	}
	if (y == 2)
	{
		cout << "请输入矩阵行数和列数:";
		cin >> m >> n;
		cout << "请输入第一个矩阵:" << endl;
		c1.input();
		cout << "请输入第两个矩阵:" << endl;
		c2.input();
		c3 = c1 - c2;
		c3.display();
	}
	if (y == 3)
	{
		cout << "请输入第一个矩阵行数和列数:";
		cin >> m >> n;
		cout << "请输入第一个矩阵:" << endl;
		c1.input();
		cout << "请输入第二个矩阵行数和列数:";
		cin >> m1 >> n1;
		cout << "请输入第两个矩阵:" << endl;
		c2.input();
		c3 = c1*c2;
		c3.display();
	}
}
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值