编译器:C++ (g++)
根据main函数中矩阵对象的定义与使用,定义相关的矩阵类Array,并利用运算符重载的方法实现矩阵的加法与输入输出操作。(为简化问题,矩阵中元素为2位以内整数,要求矩阵按照行列的格式输出,每个元素占3位宽度)
类定义:
class Array
/* 请在这里填写答案 */
测试程序样例:
int main()
{
Array arr1,arr2,arr3;
cin>>arr1;
cin>>arr2;
cout<<arr1<<endl;
cout<<arr2<<endl;
arr3=arr1+arr2;
cout<<arr3;
return 0;
}
输入样例:
1 2 3 4 5 6
7 8 9 1 11 12
输出样例:
1 2 3
4 5 6
7 8 9
1 11 12
8 10 12
5 16 18
#include <iostream>
#include <iomanip>
using namespace std;
class Array
{
public:
friend istream &operator>>(istream &in, Array &a);
friend ostream &operator<<(ostream &out, Array &a);
friend Array operator+(Array &a1, Array &a2);
private:
int x1,x2,x3;
int y1,y2,y3;
};
istream &operator>>(istream &in, Array &a)
{
in>>a.x1>>a.x2>>a.x3>>a.y1>>a.y2>>a.y3;
return in;
}
ostream &operator<<(ostream &out, Array &a)
{
out<<setw(3)<<a.x1<<setw(3)<<a.x2<<setw(3)<<a.x3<<endl;
out<<setw(3)<<a.y1<<setw(3)<<a.y2<<setw(3)<<a.y3<<endl;
return out;
}
Array operator+(Array &a1, Array &a2)
{
Array a;
a.x1 = a1.x1 + a2.x1;
a.x2 = a1.x2 + a2.x2;
a.x3 = a1.x3 + a2.x3;
a.y1 = a1.y1 + a2.y1;
a.y2 = a1.y2 + a2.y2;
a.y3 = a1.y3 + a2.y3;
return a;
}
int main()
{
Array arr1,arr2,arr3;
cin>>arr1;
cin>>arr2;
cout<<arr1<<endl;
cout<<arr2<<endl;
arr3=arr1+arr2;
cout<<arr3;
return 0;
}