C++程序设计小实验③

题目

编写程序,有两个均为3行3列的矩阵ml和m2,求两个矩阵之和。重载运算符“+”、“>>”和“<<”,使之能用于矩阵相加、输入和输出

#include <iostream>
using namespace std;

class c_arry
{
    
    

public:
	int a[3][3];
	friend istream& operator >> (istream& in, c_arry& p);    //重载运算符">>"
	friend ostream& operator << (ostream& out, c_arry& p);  //重载运算符"<<"
	friend c_arry operator+( const c_arry& b, const c_arry& c);   //重载运算符"+"
	void print();

};
c_arry x;
istream& operator >> (istream& in, c_arry& p)
{
    
    
	for (int i = 0; i < 3; i++)
	{
    
    
		for (int j = 0; j < 3; j++)
		{
    
    
			cout << "第 " << i << j << " 个元素值";
			in >> p.a[i][j];

		}
		cout << endl;
	}
	return in;

}
ostream& operator << (ostream& out, c_arry& p)
{
    
    
	for (int i = 0; i < 3; i++)
	{
    
    
		for (int j = 0; j < 3; j++)
		{
    
    
			out<< p.a[i][j];

		}
		cout << endl;
	}
	return out;

}

c_arry operator+( const c_arry& b ,const c_arry& c)
{
    
      
	
  for (int i = 0; i < 3; i++)
	{
    
    
		for (int j = 0; j < 3; j++)
			{
    
    

			 x.a[i][j]+= b.a[i][j] + c.a[i][j];

			}
		
	}
  return c_arry(x);
}

void c_arry:: print()
{
    
    

	for (int i = 0; i < 3; i++)
	{
    
    
		for (int j = 0; j < 3; j++)
		{
    
    
			cout << a[i][j]<<" ";
		}
		cout << endl;
	}

}

int main()
{
    
    
	c_arry  b, c;
	cin >> b;
	cout << "请输入第二个数组:" << endl;
	cin >> c;

	x = b + c;
	cout << "b+c= "<<endl;
	x.print();
}



Guess you like

Origin blog.csdn.net/qq_46167911/article/details/105642739